package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.help.ProUpdateHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.InvoiceErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainBatchLinkItemDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.invoice.pojo.InvoiceCommonSavePojo;
import com.xbongbong.pro.invoice.pojo.InvoiceRelationshipEditPojo;
import com.xbongbong.pro.invoice.pojo.RefTypePojo;
import com.xbongbong.pro.invoice.pojo.dto.CheckRedInvoiceDeletePojo;
import com.xbongbong.pro.invoice.pojo.dto.InvoiceDeleteBatchDTO;
import com.xbongbong.pro.invoice.pojo.dto.InvoiceGetByPurchaseIdDTO;
import com.xbongbong.pro.invoice.pojo.vo.InvoiceDeleteBatchVO;
import com.xbongbong.pro.invoice.pojo.vo.InvoiceGetByPurchaseIdVO;
import com.xbongbong.pro.invoicerelation.pojo.dto.InvoiceRelationshipDeleteBatchDTO;
import com.xbongbong.pro.listbatch.pojo.dto.AddLabelDTO;
import com.xbongbong.pro.message.constant.InvoicePushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyAddPermissionDTO;
import com.xbongbong.pro.purchaseinvoice.dto.PurchaseInvoiceAmountDetailGetDTO;
import com.xbongbong.pro.purchaseinvoice.dto.PurchaseInvoiceEditAttrUpdateDTO;
import com.xbongbong.pro.purchaseinvoice.dto.PurchaseInvoiceUpdateBatchDTO;
import com.xbongbong.pro.purchaseinvoice.dto.PurchaseInvoiceUpdateDTO;
import com.xbongbong.pro.purchaseinvoice.pojo.PurchaseInvoiceCancelOrRestorePojo;
import com.xbongbong.pro.purchaseinvoice.vo.PurchaseInvoiceAmountDetailVO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.analytical.impl.PurchaseInvoiceValidateAnalyticalServiceImpl;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.InvoiceConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PurchaseInvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseInvoiceEntityExt;
import com.xbongbong.saas.enums.BusinessFieldEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PayRelationshipEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.RefTypeEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.InvoiceCommonHelper;
import com.xbongbong.saas.help.LogHandleHelp;
import com.xbongbong.saas.help.PurchaseInvoiceHelp;
import com.xbongbong.saas.help.SaasDeleteHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.help.SaasPurchaseInvoiceHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseInvoiceRelationshipModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.service.PayPlanService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PurchaseInvoiceRelationshipService;
import com.xbongbong.saas.service.PurchaseInvoiceService;
import com.xbongbong.saas.service.PurchaseService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 进项发票业务实现
 * @author yuqian
 * @version v1.0
 * @date 2020/2/18 15:30
 * @since v1.0
 */
@Service("PurchaseInvoiceService")
public class PurchaseInvoiceServiceImpl implements PurchaseInvoiceService {

    private static final Logger LOG = LoggerFactory.getLogger(PurchaseInvoiceServiceImpl.class);

    @Resource
    private CommonHelp commonHelp;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private PurchaseInvoiceRelationshipModel purchaseInvoiceRelationshipModel;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private InvoiceCommonHelper invoiceCommonHelper;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private PayPlanSheetModel paySheetModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ProEsHelper proEsHelper;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PurchaseInvoiceRelationshipService purchaseInvoiceRelationshipService;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private ProUpdateHelp proUpdateHelp;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private PayPlanService payPlanService;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private LogHelp logHelp;
    @Resource
    private LogHandleHelp logHandleHelp;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private SaasPurchaseInvoiceHelp saasPurchaseInvoiceHelp;
    @Resource
    private PurchaseInvoiceValidateAnalyticalServiceImpl purchaseInvoiceAnalyticalService;
    @Resource
    private PurchaseInvoiceHelp purchaseInvoiceHelp;
    @Resource
    private IndexTypeModel indexTypeModel;

    /**
     * 进项发票保存前saas特殊校验
     *
     * @param validateDataDTO saas特殊校验数据入参
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/18
     */
    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        purchaseInvoiceAnalyticalService.beforeSave(validateDataDTO);
    }

    @Override
    public void afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        boolean isNew = saasFormSaveDTO.getIsNew();
        boolean isRed = false;
        Integer isImport = saasFormSaveDTO.getIsImport();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long purchaseInvoiceId = newPaasFormDataEntity.getId();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        if(newData.containsKey(PurchaseInvoiceEnum.ORIGIN_ID.getAttr())){
            Long originId = FastJsonHelper.getLongOrDefaultFromFormData(newData,PurchaseInvoiceEnum.ORIGIN_ID.getAttr(),0L);
            if(originId > 0){
                isRed = true;
            }
        }
        String corpid = saasFormSaveDTO.getCorpid();
        boolean isEnable = false;
        Long originId = FastJsonHelper.getLongOrDefaultFromFormData(newData,PurchaseInvoiceEnum.ORIGIN_ID.getAttr(),0L);
        if(isNew) {
            if (originId > BasicConstant.ZERO) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(PurchaseInvoiceEnum.HAS_RED.getAttr(), BasicConstant.ONE);
                UpdateDataEntity updateData = ExplainUtil.getUpdateData(originId, jsonObject, corpid);
                purchaseInvoiceModel.updateBatch(Collections.singletonList(updateData), corpid);
                jsonObject = new JSONObject();
                jsonObject.put(PurchaseInvoiceEnum.IS_RED.getAttr(), BasicConstant.ONE);
                UpdateDataEntity updateData1 = ExplainUtil.getUpdateData(purchaseInvoiceId, jsonObject, corpid);
                purchaseInvoiceModel.updateBatch(Collections.singletonList(updateData1), corpid);
            }
        }
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo();
            //审批的时候只能从 saasNeedPojo 拿
            if(CollectionsUtil.isNotEmpty(saasNeedRedundantAttrPojo.getAmountDetail())){
                saasFormSaveDTO.setAmountDetail(saasNeedRedundantAttrPojo.getAmountDetail());
            }
            Object purchaseNoObject = newData.get(PurchaseInvoiceEnum.PURCHASE_ID_LINK_TEXT.getAttr());
            List<String> purchaseNoList = null;
            if(Objects.nonNull(purchaseNoObject)){
                if(purchaseNoObject instanceof String[]){
                    String[]  purchaseNos = (String[]) purchaseNoObject;
                    purchaseNoList = new ArrayList<>(Arrays.asList(purchaseNos));
                }else if(purchaseNoObject instanceof List){
                    purchaseNoList = (List<String>) purchaseNoObject;
                }
            }else {
                purchaseNoList = new ArrayList<>();
            }

            InvoiceRelationshipEditPojo invoiceRelationshipEditPojo = getAddOrDeleteRelationship(newData,oldData,corpid,purchaseInvoiceId);
            //开票金额
            Double totalMoney = getDoubleOrDefaultFromFormData(newData,PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(),0D);
            Long now = (long) DateUtil.getInt();
            Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(), 0L);
            String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(newData,PurchaseInvoiceEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), "");
            if(!isNew){
                // 删除原先的的合同和回款关系，以后再改成批量更新方式
                purchaseInvoiceRelationshipModel.deleteByInvoiceId(purchaseInvoiceId, corpid);
            }
        InvoiceCommonSavePojo invoiceCommonSavePojo = new InvoiceCommonSavePojo(invoiceRelationshipEditPojo.getPurchaseIdList(),corpid,purchaseInvoiceId,originId,now,saasNeedRedundantAttrPojo,isNew,isEnable,isImport,isRed,totalMoney,saasFormSaveDTO.getAmountDetail(),newPaasFormDataEntity,saasFormSaveDTO.getLoginUser(),saasFormSaveDTO.getBusinessType(),saasFormSaveDTO.getSubBusinessType());
        boolean purchaseInvoiceFlag = saasNeedRedundantAttrPojo.isHasPurchase() && !saasNeedRedundantAttrPojo.isHasPayPlan() && !saasNeedRedundantAttrPojo.isHasPaySheet();
        boolean payPlanInvoiceFlag = saasNeedRedundantAttrPojo.isHasPayPlan() && saasNeedRedundantAttrPojo.isHasPurchase() && !saasNeedRedundantAttrPojo.isHasPaySheet();
        boolean paySheetInvoiceFlag = saasNeedRedundantAttrPojo.isHasPaySheet() && saasNeedRedundantAttrPojo.isHasPurchase() && !saasNeedRedundantAttrPojo.isHasPayPlan();
        boolean isPrePaySheetFlag = saasNeedRedundantAttrPojo.isPrePaySheet();
        try {
            if(saasNeedRedundantAttrPojo.isPurchaseUnion() || purchaseInvoiceFlag) {
                //合同不为空 其他为空 合同合并开票
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPurchaseIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PURCHASE);
                invoiceCommonSavePojo.setPurchaseNos(purchaseNoList);
                invoiceCommonSavePojo.setSupplierId(supplierId);
                invoiceCommonSavePojo.setSupplierName(supplierName);
                invoiceCommonSaveHandle(invoiceCommonSavePojo);
            }else if(saasNeedRedundantAttrPojo.isPayPlanUnion() || payPlanInvoiceFlag) {
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPayPlanIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PAYPLAN);
                invoiceCommonSavePojo.setPurchaseNos(purchaseNoList);
                invoiceCommonSavePojo.setSupplierId(supplierId);
                invoiceCommonSavePojo.setSupplierName(supplierName);
                invoiceCommonSaveHandle(invoiceCommonSavePojo);
            }else if(saasNeedRedundantAttrPojo.isPaySheetUnion() || paySheetInvoiceFlag || isPrePaySheetFlag) {
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPaySheetIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PAYSHEET);
                invoiceCommonSavePojo.setPurchaseNos(purchaseNoList);
                invoiceCommonSavePojo.setSupplierId(supplierId);
                invoiceCommonSavePojo.setSupplierName(supplierName);
                invoiceCommonSaveHandle(invoiceCommonSavePojo);
            }else {
                PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity = buildNewInvoiceRelation(false,purchaseInvoiceId,now,supplierId,supplierName, corpid,totalMoney,0L,"",0L, "",0L, "",0);
                if (Objects.nonNull(purchaseInvoiceRelationshipEntity)) {
                    try {
                        purchaseInvoiceRelationshipModel.insert(purchaseInvoiceRelationshipEntity);
                    } catch (Exception e) {
                        LOG.error("插入发票关系实体表出错", e);
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                }
                //消息推送
                purchaseInvoiceMessagePushHandle(invoiceCommonSavePojo);
            }
        } catch (XbbException e) {
            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
            LOG.error("PurchaseInvoiceServiceImpl.afterSave 执行出错：", e);
            throw e;
        }catch (Exception e){
            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
            LOG.error("PurchaseInvoiceServiceImpl.afterSave 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void invoiceCommonSaveHandle(InvoiceCommonSavePojo invoiceCommonSavePojo)throws XbbException {
        boolean isEnable = invoiceCommonSavePojo.getIsEnable();
        Integer isImport = invoiceCommonSavePojo.getIsImport();
        boolean isRed = invoiceCommonSavePojo.getIsRed();
        boolean isPrePaySheet = invoiceCommonSavePojo.getSaasNeedRedundantAttrPoJo().isPrePaySheet();
        boolean isPrePaySheetUnion = invoiceCommonSavePojo.getSaasNeedRedundantAttrPoJo().isPrePaySheetUnion();
        String payPlanNo = "";
        String paySheetNo = "";
        Long purchaseId = 0L;
        Long payPlanId = 0L;
        Long paySheetId = 0L;
        List<Long> refIdList  = invoiceCommonSavePojo.getRefIdList();
        List<Long> parentIdList = invoiceCommonSavePojo.getParentRefIdList();
        RefTypeEnum refTypeEnum = invoiceCommonSavePojo.getRefTypeEnum();
        String corpid = invoiceCommonSavePojo.getCorpid();
        List<String> purchaseNos = invoiceCommonSavePojo.getPurchaseNos();
        Map<Long,String> purchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(CollectionsUtil.isNotEmpty(parentIdList)){
            for(int i =0;i<parentIdList.size();i++){
                Long id = parentIdList.get(i);
                    String purchaseNo = purchaseNos.get(i);
                    if(Objects.isNull(purchaseNo)){
                        purchaseNo = "";
                    }
                    purchaseMap.put(id,purchaseNo);
            }
        }
        Long invoiceId = invoiceCommonSavePojo.getInvoiceId();
        JSONArray amountDetail = invoiceCommonSavePojo.getAmountDetail();
        //装采购合同id 对应的开票金额
        //装采购合同id 对应的 编号
        //Map<Long,String> purchaseSerialNo = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //装付款单 付款计划 对应的开票金额
        Map<Long,Double> subInvoiceMap = getInvoiceAmount(amountDetail,refTypeEnum,isPrePaySheet,isPrePaySheetUnion);
        int type = 0;
        Map<String, Object> amountMap;
        //这个map 给外层单次处理合同的开票数据用的
        Map<Long,Double> refPurchaseInvoiceAmount = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,Double> refPaySheetInvoiceAmount = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean isUnion = false;
        if (CollectionsUtil.isNotEmpty(refIdList)) {
            RefTypePojo refTypePojo = getRefType(refTypeEnum);
            if(Objects.nonNull(invoiceCommonSavePojo.getSaasNeedRedundantAttrPoJo())){
                switch (refTypePojo.getPurchaseInvoiceEnum()) {
                    case PURCHASE_ID:
                        isUnion = invoiceCommonSavePojo.getSaasNeedRedundantAttrPoJo().isPurchaseUnion();
                        if(isUnion){
                            type = 1;
                        }
                        break;
                    case PAY_PLAN_ID:
                        isUnion = invoiceCommonSavePojo.getSaasNeedRedundantAttrPoJo().isPayPlanUnion();
                        if(isUnion){
                            type = 2;
                        }
                        break;
                    case PAY_SHEET_ID:
                        isUnion = invoiceCommonSavePojo.getSaasNeedRedundantAttrPoJo().isPaySheetUnion();
                        //未来考虑 预收款回款单合并开票
                        if(isUnion){
                            type = 3;
                        }
                        if(isPrePaySheetUnion){
                            isUnion = isPrePaySheetUnion;
                            type = 4;
                        }
                        break;
                    default:
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216021);
                }
            }
            if(isRed){
                //红冲发票也存入关系表
                type = -1;
            }
            List<PurchaseInvoiceRelationshipEntity> purchaseRelationList = new ArrayList<>();
            //获取该发票关联的合同 id对应的合同实体
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, refTypePojo.getBusinessType(), SaasMarkEnum.SAAS.getCode());
            List<PaasFormDataEntityExt> entityExtList = paasEsModel.getByIdList(refIdList, corpid, SaasMarkEnum.SAAS.getCode(), refTypePojo.getBusinessType(), new ArrayList<>(), indexTypeEnum);
            Map<Long, PaasFormDataEntityExt> entityRefMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            entityExtList.forEach(entityExt -> entityRefMap.put(entityExt.getId(), entityExt));

            //获取除该发票外其他的关联了这个合同的关联信息 id 对应的关联信息
            Map<Long, List<PurchaseInvoiceRelationshipEntity>> oldInvoiceMap = getInvoiceMap(corpid, invoiceId, refIdList,refTypePojo.getPurchaseInvoiceEnum());
            for (int i = 0; i < refIdList.size(); i++) {
                Long refId = refIdList.get(i);
                String purchaseNo = "";
                //先将合同的编号进行处理回显
                double otherInvoiceSumAmount = 0D;
                //关联业务的实体（合同、应收款、回款单）
                PaasFormDataEntityExt paasFormDataEntityExt = entityRefMap.get(refId);
                if (Objects.isNull(paasFormDataEntityExt)) {
                    continue;
                }
                //获取以前开过票的关联实体
                List<PurchaseInvoiceRelationshipEntity> relationInvoiceList = oldInvoiceMap.get(refId);
                //获取金额明细开票的金额
                double subInvoiceAmount = subInvoiceMap.getOrDefault(refId,0D);
                if (CollectionsUtil.isNotEmpty(relationInvoiceList)) {
                    for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : relationInvoiceList) {
                        //将以前关联过这个采购合同或付款计划或付款单的发票的金额加起来
                        otherInvoiceSumAmount  = Arith.add(otherInvoiceSumAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                JSONObject refData = paasFormDataEntityExt.getData();
                //TODO 小心编号 有逗号
                String subRefNo = paasFormDataEntityExt.getSerialNo();
                if(Objects.equals(refTypeEnum,RefTypeEnum.PURCHASE)){
                    purchaseId = refId;
                }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYPLAN)){
                    purchaseId = refData.getLong(PayPlanEnum.LINK_PURCHASE.getAttr());
                    payPlanId = refId;
                    payPlanNo = subRefNo;
                }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYSHEET)){
                    if(!isPrePaySheet && !isPrePaySheetUnion) {
                        purchaseId = refData.getJSONArray(PaySheetEnum.LINK_PURCHASE.getAttr()).getLong(0);
                    }
                    paySheetId = refId;
                    paySheetNo = subRefNo;
                }
                if(Objects.nonNull(purchaseMap.get(purchaseId))){
                    purchaseNo = purchaseMap.get(purchaseId);
                }else {
                    purchaseNo = "";
                }
                //关联实体的金额（如：采购合同的金额、付款计划的金额）开票不允许超过这个金额
                Double allMoney = FastJsonHelper.getDoubleOrDefaultFromFormData(refData,refTypePojo.getAmountAttr(), 0D);
                //未开票金额
                double unInvoiceAmount;
                //已开票金额
                double invoiceAmount;
                if(!Objects.equals(isImport,BasicConstant.ONE)){
                    invoiceAmount = subInvoiceAmount;
                }else {
                    if(!isUnion){
                        //关联实体的金额（如：采购合同的金额、付款计划的金额）开票不允许超过这个金额
                        if(Objects.isNull(invoiceCommonSavePojo.getTotalMoney())){
                            invoiceAmount = 0D;
                        }else {
                            invoiceAmount = invoiceCommonSavePojo.getTotalMoney();
                        }
                    }else {
                        invoiceAmount = allMoney;
                    }
                }
                //给外层的合同开票未开票金额使用
                saasSaveHelp.addMapNormal(refPurchaseInvoiceAmount,purchaseId,invoiceAmount);
                double historyInvoiceAmount = otherInvoiceSumAmount + invoiceAmount;
                if(Objects.equals(refTypeEnum,RefTypeEnum.PAYSHEET)){
                    //和删除 作废保持一致,更新 父付款单 需要查询所有的 子付款单历史
                    saasSaveHelp.addMapTwoInvoiceAmount(refPaySheetInvoiceAmount,paasFormDataEntityExt.getUuid(),invoiceAmount);
                }
                if(!Objects.equals(refTypeEnum,RefTypeEnum.PURCHASE)){
                    proUpdateHelp.update(refTypePojo.getBusinessType(), corpid,refId,refTypePojo.getInvoiceAmountAttr(),historyInvoiceAmount);
                }else {
                    //未开票=合同总额-已开
                    unInvoiceAmount =  Arith.sub(allMoney,historyInvoiceAmount);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), unInvoiceAmount);
                    jsonObject.put(PurchaseEnum.INVOICE_AMOUNT.getAttr(), historyInvoiceAmount);
                    proUpdateHelp.update(refTypePojo.getBusinessType(), corpid, refId, jsonObject);
                }
                if (Objects.nonNull(invoiceAmount) && invoiceAmount == 0d) {
                    LOG.info("发票保存关系表有问题，参数1-corpid:{}, 参数2-amountDetail:{}, 参数3-refIdList:{}, 参数4-parentIdList:{}，参数5-refTypeEnum：{}, 参数6-subInvoiceMap:{}",
                            invoiceCommonSavePojo.getCorpid(), String.valueOf(amountDetail), refIdList, parentIdList, refTypeEnum, String.valueOf(subInvoiceMap));
                }
                PurchaseInvoiceRelationshipEntity invoiceRelationshipEntity = buildNewInvoiceRelation(isEnable, invoiceId, invoiceCommonSavePojo.getNow(), invoiceCommonSavePojo.getSupplierId(), invoiceCommonSavePojo.getSupplierName(), corpid,invoiceAmount,purchaseId,purchaseNo, payPlanId, payPlanNo,paySheetId, paySheetNo, type);
                purchaseRelationList.add(invoiceRelationshipEntity);
            }
            if(Objects.equals(refTypeEnum,RefTypeEnum.PAYSHEET)){
                //这里同步更新父回款单中 开票金额 为开票金额
                Set<String> uuidKey = refPaySheetInvoiceAmount.keySet();
                updateSumPaySheet(corpid,uuidKey,refTypePojo,refPaySheetInvoiceAmount,BasicConstant.ZERO,BasicConstant.ZERO);
            }
            if(Objects.equals(refTypeEnum,RefTypeEnum.PAYPLAN) || Objects.equals(refTypeEnum,RefTypeEnum.PAYSHEET)) {
                // 更新下关联合同的开票金额和未开票金额
                if(CollectionsUtil.isNotEmpty(parentIdList) && !isPrePaySheet && !isPrePaySheetUnion) {
                    //除这个发票以外其他同样关联的发票开票金额
                    List<PurchaseInvoiceRelationshipEntity> refInvoiceList = getRelationShipInvoice(invoiceId, corpid, parentIdList,PurchaseInvoiceEnum.PURCHASE_ID);
                    Map<Long,Double> purchaseSubAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Double otherPurchaseInvoiceMoney = 0D;
                    Double purchaseSubInoviceAmount = 0D;
                    if (CollectionsUtil.isNotEmpty(refInvoiceList)) {
                        for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : refInvoiceList) {
                            otherPurchaseInvoiceMoney = Arith.add(otherPurchaseInvoiceMoney, purchaseInvoiceRelationshipEntity.getMoney());
                            purchaseSubAmountMap.put(purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseSubAmountMap.getOrDefault(purchaseInvoiceRelationshipEntity.getPurchaseId(),0D)+purchaseInvoiceRelationshipEntity.getMoney());
                        }
                    }
                    Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    map.put("idIn", parentIdList);
                    map.put(ParameterConstant.CORPID, corpid);
                    map.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                    List<PurchaseEntityExt> purchaseEntityExtList = purchaseModel.findEntitys(map);
                    if (CollectionsUtil.isNotEmpty(purchaseEntityExtList)) {
                        for (PurchaseEntityExt purchaseEntityExt : purchaseEntityExtList) {
                            Double purchaseAmount = getDoubleOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.TOTAL_MONEY.getAttr(), 0D);
                            Double parentPurchaseInvoiceAmount = 0D;
                            parentPurchaseInvoiceAmount = refPurchaseInvoiceAmount.get(purchaseEntityExt.getId());
                            if (purchaseSubAmountMap.size() > 0) {
                                //当前合同已经 开过多少票
                                purchaseSubInoviceAmount = purchaseSubAmountMap.get(purchaseEntityExt.getId());
                            }
                            //关联合同的开票金额为其他已开票的合同金额 + 金额明细中属于这条合同的开票金额
                            if (purchaseSubInoviceAmount == null) {
                                purchaseSubInoviceAmount = 0D;
                            }
                            if (parentPurchaseInvoiceAmount == null) {
                                parentPurchaseInvoiceAmount = 0D;
                            }
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(PurchaseEnum.INVOICE_AMOUNT.getAttr(), Arith.add(purchaseSubInoviceAmount, parentPurchaseInvoiceAmount));
                            jsonObject.put(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), Arith.sub(purchaseAmount, Arith.add(purchaseSubInoviceAmount, parentPurchaseInvoiceAmount)));
                            UpdateDataEntity updateData = ExplainUtil.getUpdateData(purchaseEntityExt.getId(), jsonObject, corpid);
                            purchaseModel.updateBatch(Collections.singletonList(updateData), corpid);
                        }
                    }
                }
            }
            if (CollectionsUtil.isNotEmpty(purchaseRelationList)) {
                try {
                    purchaseInvoiceRelationshipModel.batchInsert(purchaseRelationList);
                } catch (Exception e) {
                    LOG.error("插入发票关系实体表出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
            }
        }
        //消息推送
        purchaseInvoiceMessagePushHandle(invoiceCommonSavePojo);
    }

    private void purchaseInvoiceMessagePushHandle(InvoiceCommonSavePojo invoiceCommonSavePojo) throws XbbException{
        purchaseInvoiceHelp.purchaseInvoiceMessagePushHandle(invoiceCommonSavePojo);
    }




    /**
     * 批量删除
     * @param invoiceDeleteBatchDTO
     * @return
     * @throws XbbException
     */
    @Override
    public InvoiceDeleteBatchVO deleteBatch(InvoiceDeleteBatchDTO invoiceDeleteBatchDTO) throws XbbException{
        InvoiceDeleteBatchVO invoiceDeleteBatchVO = new InvoiceDeleteBatchVO();
        String corpid = invoiceDeleteBatchDTO.getCorpid();
        List<Long> errorDataId = new ArrayList<>();
        List<String> errorDataNo = new ArrayList<>();
        Set<Long> payPlanIdSet = new HashSet<>();
        Set<Long> paySheetIdSet = new HashSet<>();
        Set<Long> purchaseIdSet = new HashSet<>();
        try{
            List<Long> idIn = invoiceDeleteBatchDTO.getDataIdList();
            Map<String, Object> param = BeanUtil.convertBean2Map(invoiceDeleteBatchDTO, true);
            param.put("idIn", idIn);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            Map<Long,String> redNoMapping = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Long> deletRedMapping = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<PurchaseInvoiceEntityExt> purchaseInvoiceList = purchaseInvoiceModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceList)) {
                for(PurchaseInvoiceEntityExt purchaseInvoiceEntityExt : purchaseInvoiceList){
                    JSONObject data = purchaseInvoiceEntityExt.getData();
                    if(Objects.nonNull(data)) {
                        if(FastJsonHelper.getLongOrDefaultFromFormData(data,PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), 0L) > 0) {
                            redNoMapping.put(purchaseInvoiceEntityExt.getId(),purchaseInvoiceEntityExt.getSerialNo());
                            deletRedMapping.put(purchaseInvoiceEntityExt.getId(),FastJsonHelper.getLongOrDefaultFromFormData(data,PurchaseInvoiceEnum.ORIGIN_ID.getAttr(),0L));
                        }
                    }
                }
            }

            //在这一步 根据要删掉的发票id去红冲发票对应原发票的mapping中 找原发票id,若删除的发票中有原单发票,即可忽略掉红冲发票
            List<Long> removeRedIds = new ArrayList<>();
            idIn.forEach(item -> {
                Long originId = deletRedMapping.get(item);
                if(idIn.contains(originId)){
                    //既包含红冲也包含原单
                    removeRedIds.add(item);
                }
            });
            if(CollectionsUtil.isNotEmpty(idIn) && CollectionsUtil.isNotEmpty(removeRedIds)) {
                idIn.removeAll(removeRedIds);
            }
            if (Objects.isNull(purchaseInvoiceList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }

            // 删除原发票关联红冲发票
            List<String> idInString = new ArrayList<>();
            idIn.forEach((id)-> idInString.add(id.toString()));
            //资金管理的新销项发票需要查金额明细才能计算删除红冲时是否会超过为开票的值
            //查询删除发票,删除操作当中是红冲发票的,这一部分需要校验 避免出现这类 问题开票60 红冲60 开票60 删除红冲60 导致出现开票120
            Map<String,Object> queryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            queryMap.put("del",BasicConstant.ZERO);
            queryMap.put("purchaseInvoiceIdIn",idIn);
            queryMap.put("isCancel",BasicConstant.ZERO);
            queryMap.put("corpid",corpid);
            queryMap.put("type",-1);
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelatEntities = purchaseInvoiceRelationshipModel.findEntitys(queryMap);
            //查一遍所有红冲发票然后根据原发票id 对应红冲发票id
            //这一步就是查询正常发票的红冲发票，删除正常发票连带他的红冲发票也会删除，如果删除的是红冲发票这一部查询不到什么。
            //查询删除发票,删除操作当中正常发票有红冲发票的
            String esData = StringConstant.JSON_DATA + StringConstant.POINT;
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termsQuery(esData +PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), idInString));
            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD , corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            fieldList.add(PurchaseInvoiceEnum.SHEET_NO.getAttr());
            fieldList.add(esData + PurchaseInvoiceEnum.TOTAL_MONEY.getAttr());
            fieldList.add(esData + PurchaseInvoiceEnum.ORIGIN_ID.getAttr());
            List<PaasFormDataEntityExt> purchaseInvoiceHasRedList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(purchaseInvoiceHasRedList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            Map<Long,Long> idMapping = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //删除操作当中正常发票有红冲发票的 红冲发票id
            List<Long> redIdIn = new ArrayList<>();
            if(!purchaseInvoiceHasRedList.isEmpty()) {
                purchaseInvoiceHasRedList.forEach((item) -> {
                    //红冲id
                    redIdIn.add(item.getDataId());
                    idMapping.put(item.getDataId(), item.getData().getLong(InvoiceEnum.ORIGIN_ID.getAttr()));
                });
            }
            //删除发票时删除操作当中红冲发票的id
            Set<Long> redPurchaseInvoiceIdSet = new HashSet<>();
            //新数据的红冲明细
            Map<Long,Map<Long,Double>> refPurchaseRedInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Map<Long,Double>> refPayPlanRedInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Map<Long,Double>> refPaySheetRedInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //采购合同 付款计划 付款单 红冲开票map
            purchaseInvoiceRelatEntities.forEach(item ->{
                if(item.getPurchaseId()>0){
                    Map<Long,Double> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if(refPurchaseRedInvoiceMap.containsKey(item.getPurchaseInvoiceId())){
                        map = refPurchaseRedInvoiceMap.getOrDefault(item.getPurchaseInvoiceId(),new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
                    }
                    saasSaveHelp.addMapNormal(map,item.getPurchaseId(),item.getMoney());
                    if(!refPurchaseRedInvoiceMap.containsKey(item.getPurchaseInvoiceId())){
                        refPurchaseRedInvoiceMap.put(item.getPurchaseInvoiceId(),map);
                    }
                }
                if(item.getPayPlanId()>0){
                    Map<Long,Double> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if(refPayPlanRedInvoiceMap.containsKey(item.getPurchaseInvoiceId())){
                        map = refPayPlanRedInvoiceMap.getOrDefault(item.getPurchaseInvoiceId(),new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
                    }
                    saasSaveHelp.addMapNormal(map,item.getPayPlanId(),item.getMoney());
                    if(!refPayPlanRedInvoiceMap.containsKey(item.getPurchaseInvoiceId())){
                        refPayPlanRedInvoiceMap.put(item.getPurchaseInvoiceId(),map);
                    }
                }
                if(item.getPaySheetId()>0){
                    Map<Long,Double> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if(refPaySheetRedInvoiceMap.containsKey(item.getPurchaseInvoiceId())){
                        map = refPaySheetRedInvoiceMap.getOrDefault(item.getPurchaseInvoiceId(),new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
                    }
                    saasSaveHelp.addMapNormal(map,item.getPaySheetId(),item.getMoney());
                    if(!refPaySheetRedInvoiceMap.containsKey(item.getPurchaseInvoiceId())){
                        refPaySheetRedInvoiceMap.put(item.getPurchaseInvoiceId(),map);
                    }
                }
                redPurchaseInvoiceIdSet.add(item.getPurchaseInvoiceId());
            });
            Map<Long,PaasFormDataEntityExt> purchaseEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,PaasFormDataEntityExt> payPlanEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,PaasFormDataEntityExt> paySheetEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> purchaseAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> payPlanAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> paySheetAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> payPlanInvoiceHistoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> paySheetInvoiceHistoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> purchaseInvoiceHistoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //这里获取
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceList)){
                for (PurchaseInvoiceEntityExt purchaseInvoiceEntityExt : purchaseInvoiceList) {
                    JSONObject data = purchaseInvoiceEntityExt.getData();
                    if(Objects.nonNull(data)){
                        //int isRed = saasUpdateHelp.getIntegerOrDefaultFromFormData(data,PurchaseInvoiceEnum.IS_RED.getAttr(),BasicConstant.ZERO);
                        //if(Objects.equals(isRed,BasicConstant.ONE)){
                            if(Objects.nonNull(data.getJSONArray(PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr()))){
                                //根据关联的关系去查
                                List<Long> idList = JSONArray.parseArray(data.getJSONArray(PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr()).toJSONString(),Long.class);
                                payPlanIdSet.addAll(idList);
                            }
                            if(Objects.nonNull(data.getJSONArray(PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr()))){
                                List<Long> idList = JSONArray.parseArray(data.getJSONArray(PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr()).toJSONString(),Long.class);
                                paySheetIdSet.addAll(idList);
                            }
                            if(Objects.nonNull(data.getJSONArray(PurchaseInvoiceEnum.PURCHASE_ID.getAttr()))){
                                List<Long> idList = JSONArray.parseArray(data.getJSONArray(PurchaseInvoiceEnum.PURCHASE_ID.getAttr()).toJSONString(),Long.class);
                                purchaseIdSet.addAll(idList);
                            }
                        //}
                    }
                }
                queryMap.remove("type");
                //都是有红冲的关联数据
                Map<Long,List<Long>> invoiceRefPurchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long,List<Long>> invoiceRefPayPlanMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long,List<Long>> invoiceRefPaySheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                //新数据的关联关系查询
                getInvoiceAmountByRelationship(payPlanIdSet,queryMap,payPlanInvoiceHistoryMap,payPlanAmountMap,invoiceRefPurchaseMap,invoiceRefPayPlanMap,invoiceRefPaySheetMap,payPlanEntityMap,InvoiceConstant.PAY_PLAN_ID_IN,corpid,XbbRefTypeEnum.PAY_PLAN);
                getInvoiceAmountByRelationship(paySheetIdSet,queryMap,paySheetInvoiceHistoryMap,paySheetAmountMap,invoiceRefPurchaseMap,invoiceRefPayPlanMap,invoiceRefPaySheetMap,paySheetEntityMap,InvoiceConstant.PAY_SHEET_ID_IN,corpid,XbbRefTypeEnum.PAY_SHEET);
                getInvoiceAmountByRelationship(purchaseIdSet,queryMap,purchaseInvoiceHistoryMap,purchaseAmountMap,invoiceRefPurchaseMap,invoiceRefPayPlanMap,invoiceRefPaySheetMap,purchaseEntityMap,InvoiceConstant.PURCHASE_ID_IN,corpid,XbbRefTypeEnum.PURCHASE);
                CheckRedInvoiceDeletePojo checkRedInvoiceDeletePojo = new CheckRedInvoiceDeletePojo(invoiceRefPurchaseMap,invoiceRefPayPlanMap,invoiceRefPaySheetMap,purchaseAmountMap,payPlanAmountMap,paySheetAmountMap,purchaseInvoiceHistoryMap,payPlanInvoiceHistoryMap,paySheetInvoiceHistoryMap,refPurchaseRedInvoiceMap,refPayPlanRedInvoiceMap,refPaySheetRedInvoiceMap);
                invoiceCommonHelper.checkRedInvoiceDelete(checkRedInvoiceDeletePojo,redPurchaseInvoiceIdSet,redNoMapping,errorDataId,errorDataNo);
            }
            if(CollectionsUtil.isNotEmpty(errorDataId)){
                Set<Long> errorDataIdSet = new HashSet<>(errorDataId);
                Set<String> errorDataNoSet = new HashSet<>(errorDataNo);
                errorDataId.clear();
                errorDataNo.clear();
                errorDataId.addAll(errorDataIdSet);
                errorDataNo.addAll(errorDataNoSet);
                idIn.removeAll(errorDataId);
                List<String> typeList = new ArrayList<>();
                typeList.add(I18nMessageUtil.getMessage(ErrorMessageConstant.REF_INVOICE_AMOUNT_NOT_ENOUGH));
                invoiceDeleteBatchVO.setErrorDataList(errorDataNo);
                invoiceDeleteBatchVO.setErrorTypeList(typeList);
                invoiceDeleteBatchVO.setErrorDataMemo(SaasDeleteHelp.getErrorDataMemo(typeList, errorDataNo));
                List<PurchaseInvoiceEntityExt> removeList = new ArrayList<>();
                for (PurchaseInvoiceEntityExt purchaseInvoiceEntityExt : purchaseInvoiceList) {
                    for(Long id : errorDataId){
                        if(Objects.equals(purchaseInvoiceEntityExt.getId(),id)){
                            removeList.add(purchaseInvoiceEntityExt);
                        }
                    }
                }
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceList) && CollectionsUtil.isNotEmpty(removeList)) {
                    purchaseInvoiceList.removeAll(removeList);
                }
            }
            //删除红冲发票
            if(!redIdIn.isEmpty()) {
                if(BasicConstant.ONE.equals(invoiceDeleteBatchDTO.getSingleFlag()) && BasicConstant.ONE.equals(redIdIn.size())){
                    purchaseInvoiceModel.deleteByKey(redIdIn.get(0),corpid);
                }else {
                    purchaseInvoiceModel.deleteBatch(redIdIn, corpid);
                }
            }
            //推送的编号
            List<String> no= new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //除去删除红冲同时还删除原发票的 所有发票　实际上删了哪些显示哪些
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceList)) {
                for (PaasFormDataEntityExt entityExt : purchaseInvoiceList) {
                    String sheetNo = entityExt.getSerialNo();
                    no.add(sheetNo);
                }
            }
            //删除所有需要删除的发票
            if(!idIn.isEmpty()) {
                if(BasicConstant.ONE.equals(invoiceDeleteBatchDTO.getSingleFlag())
                        && BasicConstant.ONE.equals(idIn.size())){
                    purchaseInvoiceModel.deleteByKey(idIn.get(0),corpid);
                }else {
                    purchaseInvoiceModel.deleteBatch(idIn, corpid);
                }
                invoiceDeleteBatchVO.setDeleteIds(idIn);
            }
            // 删除红冲发票时更新原发票hasRed字段
            //获取这次删除的红冲发票的 原始发票
            List<Long> hasOriginIdList = new ArrayList<>();
            for (PurchaseInvoiceEntityExt purchaseInvoiceEntityExt : purchaseInvoiceList) {
                Long hasOriginId = FastJsonHelper.getLongFromFormData(purchaseInvoiceEntityExt.getData(),PurchaseInvoiceEnum.ORIGIN_ID.getAttr());
                if (Objects.nonNull(hasOriginId) && !Objects.equals(hasOriginId, 0L)) {
                    hasOriginIdList.add(hasOriginId);
                }
            }
            if (!hasOriginIdList.isEmpty()) {
                //红冲有多次红冲的情况,根据原始发票id 获取不是这次删除的发票
                Map<Long, Double> redTotalMoneyByIdIn = getRedTotalMoneyByIdIn(hasOriginIdList,new ArrayList<>(redPurchaseInvoiceIdSet),corpid);
                for (Map.Entry<Long, Double> entry : redTotalMoneyByIdIn.entrySet()) {
                    hasOriginIdList.remove(entry.getKey());
                }
                //将那些只有一个红冲的原始发票的红冲状态 还原
                if (!hasOriginIdList.isEmpty()) {
                    proUpdateHelp.updateByIds(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), corpid, hasOriginIdList,PurchaseInvoiceEnum.HAS_RED.getAttr(), 0);
                }
            }
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            map.put("purchaseInvoiceIdIn",idIn);
            map.put(ParameterConstant.CORPID, invoiceDeleteBatchDTO.getCorpid());
            map.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            List<PurchaseInvoiceRelationshipEntity> invoiceRelationshipEntityList = purchaseInvoiceRelationshipModel.findEntitys(map);
            //正常发票下面的红冲发票id
            Set<Long> redInvoiceSet = idMapping.keySet();
            List<Long> ids = new ArrayList<>(redInvoiceSet);
            //查询 先要删除的金额明细 在加上 原发票有红冲的
            map.put("purchaseInvoiceIdIn",ids);
            map.put("type",-1);
            List<PurchaseInvoiceRelationshipEntity> redInvoiceRelationshipList = purchaseInvoiceRelationshipModel.findEntitys(map);
            invoiceRelationshipEntityList.addAll(redInvoiceRelationshipList);
            //现在金额明细中 普通发票 红冲发票 普通发票的所有红冲发票 作废发票(不做任何金额更改的操作)
            Map<Long,Double> deleteChangPurchaseMoneyMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> deleteChangPayPlanMoneyMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> deleteChangPaySheetMoneyMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntityList)){
                for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : invoiceRelationshipEntityList){
                    if(!Objects.equals(purchaseInvoiceRelationshipEntity.getPurchaseId(),0L)){
                        saasSaveHelp.addMapNormal(deleteChangPurchaseMoneyMap,purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseInvoiceRelationshipEntity.getMoney());
                    }
                    if(!Objects.equals(purchaseInvoiceRelationshipEntity.getPayPlanId(),0L)){
                        saasSaveHelp.addMapNormal(deleteChangPayPlanMoneyMap,purchaseInvoiceRelationshipEntity.getPayPlanId(),purchaseInvoiceRelationshipEntity.getMoney());
                    }
                    if(!Objects.equals(purchaseInvoiceRelationshipEntity.getPaySheetId(),0L)){
                        saasSaveHelp.addMapNormal(deleteChangPaySheetMoneyMap,purchaseInvoiceRelationshipEntity.getPaySheetId(),purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
            }
            List<UpdateDataEntity> purchaseUpdateDataList = invoiceCommonHelper.deleteInvoiceGetAmount(corpid,purchaseInvoiceHistoryMap,deleteChangPurchaseMoneyMap,purchaseEntityMap,XbbRefTypeEnum.PURCHASE.getCode());
            List<UpdateDataEntity> payPlanUpdateDataList = invoiceCommonHelper.deleteInvoiceGetAmount(corpid,payPlanInvoiceHistoryMap,deleteChangPayPlanMoneyMap,payPlanEntityMap,XbbRefTypeEnum.PAY_PLAN.getCode());
            List<UpdateDataEntity> paySheetUpdateDataList = invoiceCommonHelper.deleteInvoiceGetAmount(corpid,paySheetInvoiceHistoryMap,deleteChangPaySheetMoneyMap,paySheetEntityMap,XbbRefTypeEnum.PAY_SHEET.getCode());
            if(CollectionsUtil.isNotEmpty(purchaseUpdateDataList)) {
                purchaseModel.updateBatch(purchaseUpdateDataList, corpid);
            }
            if(CollectionsUtil.isNotEmpty(payPlanUpdateDataList)){
                payPlanModel.updateBatch(payPlanUpdateDataList,corpid);
            }
            if(CollectionsUtil.isNotEmpty(paySheetUpdateDataList)){
                paySheetModel.updateBatch(paySheetUpdateDataList,corpid);
            }
            //要更新
            /*Map<Long,List<PurchaseInvoiceRelationshipEntity>> relationshipMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            invoiceRelationshipEntityList.forEach(invoiceRelationshipEntity -> {
                //若是红冲map
                if(idMapping.containsKey(invoiceRelationshipEntity.getPurchaseInvoiceId())){
                    Long originId = idMapping.getOrDefault(invoiceRelationshipEntity.getPurchaseInvoiceId(),0L);
                    if(relationshipMap.containsKey(originId)){
                        if(relationshipMap.containsKey(originId)){
                            List<PurchaseInvoiceRelationshipEntity> invoiceRelationshipEntities = relationshipMap.getOrDefault(originId,new ArrayList<>());
                            invoiceRelationshipEntities.add(invoiceRelationshipEntity);
                        }else {
                            List<PurchaseInvoiceRelationshipEntity> invoiceRelationshipEntities = new ArrayList<>();
                            invoiceRelationshipEntities.add(invoiceRelationshipEntity);
                            relationshipMap.put(invoiceRelationshipEntity.getPurchaseInvoiceId(),invoiceRelationshipEntities);
                        }
                    }else {
                        List<PurchaseInvoiceRelationshipEntity> invoiceRelationshipEntities = new ArrayList<>();
                        invoiceRelationshipEntities.add(invoiceRelationshipEntity);
                        relationshipMap.put(originId,invoiceRelationshipEntities);
                    }
                }else {
                    saasSaveHelp.putPurchaseInvoiceRelationshipMap(relationshipMap,invoiceRelationshipEntity);
                }
            });*/

            // 删除发票关联
            InvoiceRelationshipDeleteBatchDTO invoiceRelationshipDeleteBatchDTO = new InvoiceRelationshipDeleteBatchDTO();
            BeanUtil.copyProperties(invoiceDeleteBatchDTO, invoiceRelationshipDeleteBatchDTO);
            idIn.addAll(redIdIn);
            if(CollectionsUtil.isNotEmpty(idIn)) {
                invoiceRelationshipDeleteBatchDTO.setInvoiceIdIn(idIn);
                purchaseInvoiceRelationshipService.deleteBatchByInvoiceIdIn(invoiceRelationshipDeleteBatchDTO);
            }
            // 删除发票消息推送
            for (PurchaseInvoiceEntityExt purchaseInvoiceEntityExt : purchaseInvoiceList) {
                // 消息推送
                Long dataId = purchaseInvoiceEntityExt.getId();
                List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.PURCHASE_INVOICE_DEL_PUSH.getCode(), PushTypeEnum.PURCHASE_INVOICE_DEL_PUSH.getSubCode(), invoiceDeleteBatchDTO.getLoginUser(),purchaseInvoiceEntityExt);
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(purchaseInvoiceEntityExt.getAppId(), purchaseInvoiceEntityExt.getMenuId(), purchaseInvoiceEntityExt.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(InvoicePushConstant.PURCHASE_INVOICE_DEL_TITLE), String.format(I18nMessageUtil.getMessage(InvoicePushConstant.PURCHASE_INVOICE_DEL_CONTENT), invoiceDeleteBatchDTO.getLoginUser().getName(), purchaseInvoiceEntityExt.getSerialNo()), null, options);
                baseProducer.sendMessage(PushTypeEnum.PURCHASE_INVOICE_DEL_PUSH, messageRabbitMqDTO);
            }

            OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
            if (Objects.equals(1, invoiceDeleteBatchDTO.getIsBusinessRule())) {
                operateTypeEnum = OperateTypeEnum.RULE_DELETE;
            }
            //生成删除日志(区分单个删除和批量删除)
            String userId = invoiceDeleteBatchDTO.getUserId();
            String userName = invoiceDeleteBatchDTO.getLoginUserName();
            String nameStr = StringUtils.join(no, "，");
            if(idIn.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.PURCHASE_INVOICE.getName(), idIn.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(PurchaseInvoiceEnum.SHEET_NO.getAttrName());
                infoArrPojo.setContent(nameStr);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.PURCHASE_INVOICE, operateTypeEnum,
                        "", "", memo, invoiceDeleteBatchDTO.getHttpHeader());
            } else if (Objects.equals(idIn.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.PURCHASE_INVOICE.getName(), nameStr);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PURCHASE_INVOICE, operateTypeEnum,
                        idIn.get(0).toString(), nameStr, memo, invoiceDeleteBatchDTO.getHttpHeader());
            }

        }catch (XbbException e) {
            rollBack4LinkEs(invoiceDeleteBatchDTO.getDataIdList(), corpid, purchaseIdSet, payPlanIdSet, paySheetIdSet);
            throw e;
        }catch (Exception e) {
            rollBack4LinkEs(invoiceDeleteBatchDTO.getDataIdList(), corpid, purchaseIdSet, payPlanIdSet, paySheetIdSet);
            LOG.error("invoiceServiceImp.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return invoiceDeleteBatchVO;
    }

    /**
     * 进项发票删除失败、新增发票失败回滚关联业务的es - 同步数据库数据至es（需确保失败后数据库事务回滚结束才同步es）
     * 注：删除的还需回滚发票本身为删除之前的状态
     * @param dataIdList 发票数据id集合
     * @param corpid 公司id
     * @param contractIdIn 关联采购合同id
     * @param planIdIn 关联付款计划id
     * @param sheetIdIn 关联付款单id
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void rollBack4LinkEs(List<Long> dataIdList, String corpid, Collection<Long> contractIdIn, Collection<Long> planIdIn, Collection<Long> sheetIdIn) {
        threadPoolBeanConfig.addUpdateDelThreadPool().execute(() -> {
            try {
                //需要查数据库同步至es内，因此睡眠一小会，确保事务回滚完毕数据库恢复到操作之前的状态
                Thread.sleep(1000L);
                updateRollback(dataIdList, corpid);
                payPlanService.updateRollback(planIdIn, corpid);
                purchaseService.updateRollback(contractIdIn, corpid);
                payPlanSheetService.updateRollback(sheetIdIn, corpid);
            } catch (XbbException | InterruptedException e1) {
                LOG.error("PurchaseInvoiceServiceImpl.rollBack4LinkEs rollback" + e1);
                // 恢复中断状态
                Thread.currentThread().interrupt();
            }
        });
    }

    @Override
    public void dataConsistencyUpdateSupplier(String corpid, Long supplierId, String supplierName){
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery(PurchaseInvoiceEnum.getEsAttr4Keyword(PurchaseInvoiceEnum.SUPPLIER_NAME), supplierId));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            List<PurchaseInvoiceEntityExt> purchaseInvoiceEntityExtList = purchaseInvoiceModel.findEntitys(param);

            if (Objects.nonNull(purchaseInvoiceEntityExtList) && !purchaseInvoiceEntityExtList.isEmpty()) {
                List<PurchaseInvoiceUpdateDTO> purchaseInvoiceUpdateDTOList = new ArrayList<>();
                for (PurchaseInvoiceEntityExt entityExt : purchaseInvoiceEntityExtList) {
                    PurchaseInvoiceUpdateDTO purchaseInvoiceUpdateDTO = new PurchaseInvoiceUpdateDTO();
                    purchaseInvoiceUpdateDTO.setId(entityExt.getId());
                    JSONObject data = new JSONObject();
                    data.put(PurchaseInvoiceEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), supplierName);
                    purchaseInvoiceUpdateDTO.setData(data);
                    purchaseInvoiceUpdateDTOList.add(purchaseInvoiceUpdateDTO);
                }
                PurchaseInvoiceUpdateBatchDTO purchaseInvoiceUpdateBatchDTO = new PurchaseInvoiceUpdateBatchDTO();
                purchaseInvoiceUpdateBatchDTO.setCorpid(corpid);
                purchaseInvoiceUpdateBatchDTO.setInvoiceList(purchaseInvoiceUpdateDTOList);
                updateBatch(purchaseInvoiceUpdateBatchDTO);
            }

        } catch (Exception e) {
            LOG.error("PurchaseInvoiceServiceImpl.dataConsistencyUpdateSupplier 出错，corpid=" + corpid + "  supplierId=" + supplierId + " supplierName=" + supplierName, e);
        }
    }

    private void updateBatch(PurchaseInvoiceUpdateBatchDTO purchaseInvoiceUpdateBatchDTO) throws XbbException {
        try {
            String corpid = purchaseInvoiceUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<PurchaseInvoiceUpdateDTO> returnedPurchaseList = purchaseInvoiceUpdateBatchDTO.getInvoiceList();
            if (Objects.nonNull(returnedPurchaseList) && !returnedPurchaseList.isEmpty()) {
                returnedPurchaseList.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                purchaseInvoiceModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("purchaseInvoiceService.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 根据金额明细获取开票金额
     * @param set
     * @param queryMap
     * @param invoiceHistoryMap
     * @param amountMap
     * @param invoiceRefPurchaseMap
     * @param invoiceRefPayPlanMap
     * @param invoiceRefPaySheetMap
     * @param attr
     * @param corpid
     * @param xbbRefTypeEnum
     * @throws XbbException
     */
    private void getInvoiceAmountByRelationship(Set<Long> set,Map<String,Object> queryMap,Map<Long,Double> invoiceHistoryMap,Map<Long,Double> amountMap,
                                                Map<Long,List<Long>> invoiceRefPurchaseMap,Map<Long,List<Long>> invoiceRefPayPlanMap,Map<Long,List<Long>> invoiceRefPaySheetMap,Map<Long,PaasFormDataEntityExt> entityExtMap,String attr,String corpid,XbbRefTypeEnum xbbRefTypeEnum) throws XbbException{
        if(CollectionsUtil.isNotEmpty(set)){
            queryMap.remove("purchaseInvoiceIdIn");
            queryMap.put(attr,set);
            List<PurchaseInvoiceRelationshipEntity> refInvoiceList = purchaseInvoiceRelationshipModel.findEntitys(queryMap);
            queryMap.remove(attr);
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)) {
                refInvoiceList.forEach(item -> {
                    saasSaveHelp.addMapNormal(invoiceHistoryMap, item.getPayPlanId(), item.getMoney());
                    List<Long> payPanIdList = new ArrayList<>();
                    List<Long> purchaseIdList = new ArrayList<>();
                    payPanIdList.add(item.getPayPlanId());
                    purchaseIdList.add(item.getPurchaseId());
                    if(CollectionsUtil.isNotEmpty(payPanIdList)) {
                        invoiceRefPayPlanMap.put(item.getPurchaseInvoiceId(), payPanIdList);
                    }
                    if(CollectionsUtil.isNotEmpty(purchaseIdList)) {
                        invoiceRefPurchaseMap.put(item.getPurchaseInvoiceId(), purchaseIdList);
                    }
                });
            }
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)) {
                refInvoiceList.forEach(item -> {
                    saasSaveHelp.addMapNormal(invoiceHistoryMap, item.getPaySheetId(), item.getMoney());
                    List<Long> paySheetIdList = new ArrayList<>();
                    List<Long> purchaseIdList = new ArrayList<>();
                    paySheetIdList.add(item.getPaySheetId());
                    purchaseIdList.add(item.getPurchaseId());
                    if(CollectionsUtil.isNotEmpty(paySheetIdList)){
                        invoiceRefPaySheetMap.put(item.getPurchaseInvoiceId(),paySheetIdList);
                    }
                    if(CollectionsUtil.isNotEmpty(purchaseIdList)){
                        invoiceRefPurchaseMap.put(item.getPurchaseInvoiceId(),purchaseIdList);
                    }
                });
            }
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PURCHASE)) {
                refInvoiceList.forEach(item -> {
                    saasSaveHelp.addMapNormal(invoiceHistoryMap, item.getPurchaseId(), item.getMoney());
                    List<Long> purchaseIdList = new ArrayList<>();
                    purchaseIdList.add(item.getPurchaseId());
                    if(CollectionsUtil.isNotEmpty(purchaseIdList)){
                        invoiceRefPurchaseMap.put(item.getPurchaseInvoiceId(),purchaseIdList);
                    }
                });
            }
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("corpid",corpid);
            map.put("del",BasicConstant.ZERO);
            if(Objects.isNull(amountMap)){
                amountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            }
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PURCHASE)){
                map.put("idIn",set);
                List<PurchaseEntityExt> purchaseEntityExtList = purchaseModel.findEntitys(map);
                for(PurchaseEntityExt purchaseEntityExt : purchaseEntityExtList) {
                    entityExtMap.put(purchaseEntityExt.getId(),purchaseEntityExt);
                    amountMap.put(purchaseEntityExt.getId(), getDoubleOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.TOTAL_MONEY.getAttr(), 0D));
                }
            }
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
                map.put("idIn",set);
                List<PayPlanEntityExt> payPlanEntityExts = payPlanModel.findEntitys(map);
                for(PayPlanEntityExt payPlanEntityExt : payPlanEntityExts){
                    entityExtMap.put(payPlanEntityExt.getId(),payPlanEntityExt);
                    amountMap.put(payPlanEntityExt.getId(), getDoubleOrDefaultFromFormData(payPlanEntityExt.getData(), PayPlanEnum.AMOUNT.getAttr(), 0D));
                }
            }
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                map.put("idIn",set);
                List<PayPlanSheetEntityExt> paySheetEntityExts = paySheetModel.findEntitys(map);
                for(PayPlanSheetEntityExt paySheetEntityExt : paySheetEntityExts){
                    entityExtMap.put(paySheetEntityExt.getId(),paySheetEntityExt);
                    amountMap.put(paySheetEntityExt.getId(),getDoubleOrDefaultFromFormData(paySheetEntityExt.getData(),PaySheetEnum.AMOUNT.getAttr(),0D));
                }
            }
        }
    }

    @Override
    public void updateRollback(List<Long> idIn, String corpid) throws XbbException {
        if (Objects.isNull(idIn) || idIn.isEmpty()) {
            return;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("idIn", idIn);
        param.put(StringConstant.CORPID, corpid);
        List<PurchaseInvoiceEntityExt> purchaseInvoiceList = purchaseInvoiceModel.findEntitysWithoutSub(param);
        if (Objects.nonNull(purchaseInvoiceList)) {
            for (PurchaseInvoiceEntityExt item : purchaseInvoiceList) {
                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                BeanUtil.copyProperties(item, paasFormDataEntity);
                proEsHelper.reductionEsInUpdate(paasFormDataEntity, item.getId(), corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
            }
        }
    }




    /**
     * 新建时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        explainList.forEach((item) -> {
            if (Objects.equals(item.getAttr(),PurchaseInvoiceEnum.APPLY_USER.getAttr())) {
                item.setDefaultAttr(defaultAttrHelp.setUserDefaultAttrPoJo(formatExplainDTO.getUserId(), formatExplainDTO.getLoginUser().getName(),formatExplainDTO.getLoginUser().getAvatar()));
            }
        });
    }

    @Override
    public void formatExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO, List<FieldAttrEntityForImport> fieldAttrList) {
        paasFormDataESList.forEach(item ->{
            JSONObject data = item.getData();
            Integer isRed = data.getInteger(PurchaseInvoiceEnum.IS_RED.getAttr());
            Integer isCancel = data.getInteger(PurchaseInvoiceEnum.IS_CANCEL.getAttr());
            if (Objects.equals(isRed, BasicConstant.ONE)) {
                data.put(PurchaseInvoiceEnum.IS_RED.getAttr(), I18nMessageUtil.getMessage(CommonConstant.YES));
            } else {
                data.put(PurchaseInvoiceEnum.IS_RED.getAttr(), "");
            }
            if (Objects.equals(isCancel, BasicConstant.ONE)) {
                data.put(PurchaseInvoiceEnum.IS_CANCEL.getAttr(),I18nMessageUtil.getMessage(CommonConstant.YES));
            } else {
                data.put(PurchaseInvoiceEnum.IS_CANCEL.getAttr(), "");
            }
        });
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException{
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        formDataAddDTO.setSerialNo("");
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);

        Long linkSupplierId = 0L;
        List<PaasFormDataEntityExt> paasFormDataEntityExts = new ArrayList<>();
        List<Long> idList = new ArrayList<>();
        String payRelationship = null;
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                continue;
            }
            if (Objects.equals(attr,PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr())) {
                JSONObject jsonObject = new JSONObject();
                importHelper.formatDropDownValue4Import(jsonObject, fieldAttr, cellValue);
                payRelationship = jsonObject.getString(attr);
            }
        }
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(attr,PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr())) {
                // 关联客户根据linkedType判断
                linkSupplierId = importHelper.formatSuppplier2SupplierId(cellValue.toString(), dataJson, fieldAttr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttr, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttr.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else {
                    if (Objects.equals(attr,PurchaseInvoiceEnum.PURCHASE_ID.getAttr())) {
                        //去重
                        cellValue = importHelper.removeDuplicatesCellValue(cellValue);
                        paasFormDataEntityExts = importHelper.formatMultiRelyBusiness(linkSupplierId, dataJson, fieldAttr, cellValue,PurchaseEnum.SUPPLIER_ID.getAttr());
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                            paasFormDataEntityExts.forEach(item -> {
                                idList.add(item.getId());
                            });
                        }
                    } else if (Objects.equals(attr,PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr())) {
                        if(CollectionsUtil.isEmpty(paasFormDataEntityExts)){
                            throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217012);
                        }
                        if(Objects.equals(payRelationship,PayRelationshipEnum.PAY_SHEET.getCode())){
                            throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217011);
                        }
                        //去重
                        cellValue = importHelper.removeDuplicatesCellValue(cellValue);
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                            importHelper.formatInvoiceMultiRelyBusiness(idList, dataJson, fieldAttr, cellValue, PayPlanEnum.LINK_PURCHASE.getAttr());
                        }
                    } else if(Objects.equals(attr,PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr())){
                        if(CollectionsUtil.isEmpty(paasFormDataEntityExts)){
                            throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217012);
                        }
                        if(Objects.equals(payRelationship,PayRelationshipEnum.PAY_PLAN.getCode())){
                            throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217011);
                        }
                        //去重
                        cellValue = importHelper.removeDuplicatesCellValue(cellValue);
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                            importHelper.formatInvoiceMultiRelyBusiness(Collections.singletonList(linkSupplierId), dataJson, fieldAttr, cellValue, PaySheetEnum.LINK_SUPPLIER.getAttr());
                        }
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                            importHelper.checkInvoiceMultiRelyBusiness(idList,fieldAttr,cellValue,PaySheetEnum.LINK_PURCHASE.getAttr());
                        }
                    }else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                        formDataAddDTO.setSerialNo(cellValue.toString());
                    } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                        importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                    } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                        importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                    } else {
                        dataJson.put(attr, cellValue);
                    }
                }
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public void updateInvoiceMoney(String corpid, PurchaseInvoiceCancelOrRestorePojo purchaseInvoiceCancelOrRestorePojo, Integer isCancel, Integer isDelete, Integer businessType) throws XbbException {
        List<PaasFormDataEntityExt> purchaseList = null;
        List<PaasFormDataEntityExt> payPlanList = new ArrayList<>();
        List<PaasFormDataEntityExt> paySheetList = new ArrayList<>();
       if(!Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode())){
            if(Objects.equals(businessType,XbbRefTypeEnum.PAY_PLAN.getCode())){
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceCancelOrRestorePojo.getPayPlanIdList())) {
                    payPlanList = paasEsModel.getByIdList(purchaseInvoiceCancelOrRestorePojo.getPayPlanIdList(), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PAY_PLAN.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_PAY_PLAN);
                }
            }else if(Objects.equals(businessType,XbbRefTypeEnum.PAY_SHEET.getCode())){
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceCancelOrRestorePojo.getPaySheetIdList())) {
                    paySheetList = paasEsModel.getByIdList(purchaseInvoiceCancelOrRestorePojo.getPaySheetIdList(), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PAY_SHEET.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
                }
            }
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceCancelOrRestorePojo.getPurchaseIdList())) {
                purchaseList = paasEsModel.getByIdList(purchaseInvoiceCancelOrRestorePojo.getPurchaseIdList(), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PURCHASE.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_PURCHASE);
            }
        }else {
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceCancelOrRestorePojo.getPurchaseIdList())) {
                purchaseList = paasEsModel.getByIdList(purchaseInvoiceCancelOrRestorePojo.getPurchaseIdList(), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PURCHASE.getCode(), new ArrayList<>(), IndexTypeEnum.IDX_SAAS_PURCHASE);
            }
        }
        List<PaasFormDataEntityExt> entityList = new ArrayList<>();
        RefTypePojo refTypePojo = new RefTypePojo();
        if(CollectionsUtil.isNotEmpty(payPlanList)){
            entityList = payPlanList;
            refTypePojo = getRefType(RefTypeEnum.PAYPLAN);
        }else if(CollectionsUtil.isNotEmpty(paySheetList)){
            refTypePojo = getRefType(RefTypeEnum.PAYSHEET);
            entityList = paySheetList;
        }
        Map<String,Double> subPaySheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
       for (PaasFormDataEntityExt entityExt : entityList) {
           updatePurchaseOrPayPlanOrSheetIsCancel(entityExt, isCancel,isDelete,corpid, purchaseInvoiceCancelOrRestorePojo, refTypePojo,subPaySheetMap);
        }
        //如果是回款单还需要更新父回款单
        if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_SHEET_ID)){
            Set<String> uuidKey = subPaySheetMap.keySet();
            updateSumPaySheet(corpid,uuidKey,refTypePojo,subPaySheetMap,isCancel,isDelete);
        }
        if(CollectionsUtil.isNotEmpty(purchaseList)){
            refTypePojo = getRefType(RefTypeEnum.PURCHASE);
            for (PaasFormDataEntityExt entityExt : purchaseList) {
                updatePurchaseOrPayPlanOrSheetIsCancel(entityExt,isCancel,isDelete,corpid,purchaseInvoiceCancelOrRestorePojo,refTypePojo,null);
            }
        }
    }

    private void updatePurchaseOrPayPlanOrSheetIsCancel(PaasFormDataEntityExt entity,Integer isCancel,Integer isDelete,String corpid,PurchaseInvoiceCancelOrRestorePojo purchaseInvoiceCancelOrRestorePojo,RefTypePojo refTypePojo,Map<String,Double> subPaySheetMap) throws XbbException{
        if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_PLAN_ID) || Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_SHEET_ID)) {
            Map<Long,Double> refMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_PLAN_ID)){
                refMap = purchaseInvoiceCancelOrRestorePojo.getPayPlanRefMap();
            }else if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_SHEET_ID)){
                refMap = purchaseInvoiceCancelOrRestorePojo.getPaySheetRefMap();
            }
            Double invoiceAmount = refMap.getOrDefault(entity.getId(),0D);
            if (Objects.equals(isCancel, 1) || Objects.equals(isDelete,BasicConstant.ONE)) {
                //付款计划或回款单开的发票 减去这次开的
                double historyInvoiceAmount = Arith.sub(getDoubleOrDefaultFromFormData(entity.getData(), refTypePojo.getInvoiceAmountAttr(), 0D), invoiceAmount);
                proUpdateHelp.update(refTypePojo.getBusinessType(), corpid, entity.getId(),refTypePojo.getInvoiceAmountAttr(),historyInvoiceAmount);
                if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_SHEET_ID) && Objects.equals(entity.getAlone(), SheetAloneEnum.CHILD.getCode())) {
                    saasSaveHelp.addMapTwoInvoiceAmount(subPaySheetMap, entity.getUuid(),invoiceAmount);
                }
            } else {
                double historyInvoiceAmount = Arith.add(getDoubleOrDefaultFromFormData(entity.getData(), refTypePojo.getInvoiceAmountAttr(), 0D),invoiceAmount);
                proUpdateHelp.update(refTypePojo.getBusinessType(), corpid, entity.getId(),refTypePojo.getInvoiceAmountAttr(),historyInvoiceAmount);
                if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PAY_SHEET_ID) && Objects.equals(entity.getAlone(), SheetAloneEnum.CHILD.getCode())) {
                    saasSaveHelp.addMapTwoInvoiceAmount(subPaySheetMap, entity.getUuid(),invoiceAmount);
                }
            }
        }
        if(Objects.equals(refTypePojo.getPurchaseInvoiceEnum(),PurchaseInvoiceEnum.PURCHASE_ID)) {
            //采购合同逻辑不一样 采购合同有两个付款计划出自同一采购合同
            JSONObject jsonObject = new JSONObject();
            Map<Long,Double> purchaseInvoiceMap = purchaseInvoiceCancelOrRestorePojo.getPurchaseMap();
            Double purchaseInvoiceMoney = purchaseInvoiceMap.getOrDefault(entity.getId(),0D);
            if (Objects.equals(isCancel, BasicConstant.ONE) || Objects.equals(isDelete,BasicConstant.ONE)) {
                //这个次发票相关关联明细,这次开的金额作废,所以合同开票金额= 合同开票金额 - 这次开的金额
                jsonObject.put(refTypePojo.getInvoiceAmountAttr(), Arith.sub(getDoubleOrDefaultFromFormData(entity.getData(), refTypePojo.getInvoiceAmountAttr(), 0D),purchaseInvoiceMoney));
                jsonObject.put(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), Arith.add(getDoubleOrDefaultFromFormData(entity.getData(),PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), 0D),purchaseInvoiceMoney));
            } else {
                jsonObject.put(refTypePojo.getInvoiceAmountAttr(), Arith.add(getDoubleOrDefaultFromFormData(entity.getData(), refTypePojo.getInvoiceAmountAttr(), 0D), purchaseInvoiceMoney));
                jsonObject.put(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), Arith.sub(getDoubleOrDefaultFromFormData(entity.getData(),PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), 0D),purchaseInvoiceMoney));
            }
            proUpdateHelp.update(refTypePojo.getBusinessType(),corpid,entity.getId(),jsonObject);
        }
    }


    @Override
    public Map<String, Object> getRelationMapForJudgeMoney(boolean isHasPaySheet,boolean isPrePaySheet,boolean isPrePaySheetUnion,boolean isHasPayPlan,String corpid, List<Long> purchaseIds, List<Long> refIds) throws XbbException {
        return saasPurchaseInvoiceHelp.getRelationMapForJudgeMoney(isHasPaySheet, isPrePaySheet, isPrePaySheetUnion, isHasPayPlan, corpid, purchaseIds, refIds);
    }

    /**
     * 获取发票明细中开票的金额 组成一个id对应的map
     * @param amountDetail
     * @param refTypeEnum
     * @return
     */
    private Map<Long,Double> getInvoiceAmount(JSONArray amountDetail,RefTypeEnum refTypeEnum,boolean isPrePaySheet,boolean isPrePaySheetUnion) {
        Map<Long,Double> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Long dataId = null;
        Double invoiceAmount;
        JSONObject purchaseObject = new JSONObject();
        if(CollectionsUtil.isNotEmpty(amountDetail)){
            for(int i=0;i<amountDetail.size();i++){
                JSONObject amountObject = amountDetail.getJSONObject(i);
                invoiceAmount = amountObject.getDouble(InvoiceConstant.INVOICE_AMOUNT);
                if(!isPrePaySheet && !isPrePaySheetUnion) {
                    JSONArray purchaseRef = amountObject.getJSONArray(InvoiceConstant.PURCHASE);
                    if(CollectionsUtil.isNotEmpty(purchaseRef) && purchaseRef.size()>BasicConstant.ZERO){
                        purchaseObject = purchaseRef.getJSONObject(0);
                    }
                    if(Objects.nonNull(purchaseObject)){
                        dataId = purchaseObject.getLong(BasicConstant.ID);
                    }
                }
                if(Objects.equals(refTypeEnum,RefTypeEnum.PAYPLAN)){
                    JSONArray payPlanRef = amountObject.getJSONArray(InvoiceConstant.PAYPLAN);
                    if(CollectionsUtil.isNotEmpty(payPlanRef) && payPlanRef.size()>BasicConstant.ZERO){
                        JSONObject payPlanObject = payPlanRef.getJSONObject(0);
                        if(Objects.nonNull(payPlanObject)){
                            dataId = payPlanObject.getLong(BasicConstant.ID);
                        }
                    }
                }else if(Objects.equals(refTypeEnum,RefTypeEnum.PAYSHEET)){
                    JSONArray paySheetRef = amountObject.getJSONArray(InvoiceConstant.PAYSHEET);
                    if(CollectionsUtil.isNotEmpty(paySheetRef) && paySheetRef.size()>BasicConstant.ZERO){
                        JSONObject paySheetObject = paySheetRef.getJSONObject(0);
                        if(Objects.nonNull(paySheetObject)){
                            dataId = paySheetObject.getLong(BasicConstant.ID);
                        }
                    }
                }
                if(dataId!=null){
                    map.put(dataId,invoiceAmount);
                }
            }
        }
        return map;
    }

     /** 建立发票关系
     *
             * @param isEnable     是否审批
     * @param purchaseInvoiceId    发票id
     * @param now          时间
     * @param supplierId   客户id
     * @param supplierName 客户名称
     * @param corpid       公司id
     * @param money        金额
     * @param purchaseId   合同id
     * @param purchaseNo   合同编号
     * @param payPlanId    回款id
     * @param payPlanNo    回款编号
     * @param type         类性
     * @throws XbbException 异常
     */
    private PurchaseInvoiceRelationshipEntity buildNewInvoiceRelation(boolean isEnable, Long purchaseInvoiceId, Long now, Long supplierId, String supplierName, String corpid, Double money, Long purchaseId, String purchaseNo, Long payPlanId, String payPlanNo,Long paySheetId,String paySheetNo,Integer type) throws XbbException {
       return purchaseInvoiceHelp.buildNewInvoiceRelation(isEnable, purchaseInvoiceId, now, supplierId, supplierName, corpid, money, purchaseId, purchaseNo, payPlanId, payPlanNo, paySheetId, paySheetNo, type);
    }

    private void updateSumPaySheet(String corpid, Collection uuids,RefTypePojo refTypePojo,Map<String,Double> refPaySheetInvoiceAmount,Integer isCancel,Integer isDelete) throws XbbException{
        List<PaasFormDataEntityExt> paySheetEntityExtList = fundHelp.getParentAndChildEsDataListByUuids(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET, corpid, uuids);
        if(CollectionsUtil.isNotEmpty(paySheetEntityExtList)) {
            List<Long> subPaySheetIdList = new ArrayList<>();
            Map<Long,String> subUuidMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, Long> uuidMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,Double> parentInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(PaasFormDataEntityExt paySheetEntityExt : paySheetEntityExtList) {
                if(Objects.equals(paySheetEntityExt.getAlone(),SheetAloneEnum.CHILD.getCode())){
                    subUuidMap.put(paySheetEntityExt.getId(),paySheetEntityExt.getUuid());
                    subPaySheetIdList.add(paySheetEntityExt.getId());
                }
                if (Objects.equals(paySheetEntityExt.getAlone(), SheetAloneEnum.PARENT.getCode())) {
                    uuidMap.put(paySheetEntityExt.getUuid(), paySheetEntityExt.getId());
                }
            }
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(InvoiceConstant.PAY_SHEET_ID_IN,subPaySheetIdList);
            map.put("corpid",corpid);
            map.put("isCancel",BasicConstant.ZERO);
            map.put(InvoiceConstant.DEL,BasicConstant.ZERO);
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(map);
            for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities){
                String uuid = subUuidMap.get(purchaseInvoiceRelationshipEntity.getPaySheetId());
                saasSaveHelp.addMapNormal(parentInvoiceMap,uuidMap.getOrDefault(uuid,0L),purchaseInvoiceRelationshipEntity.getMoney());
            }
            //如果是子付款单则需要其他子付款单的开票信息
            Iterator<Map.Entry<String, Long>> it = uuidMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Long> entry = it.next();
                String uuid = entry.getKey();
                Long parentId = entry.getValue();
                //父的付款单总开票金额
                double historyInvoiceAmount = parentInvoiceMap.getOrDefault(parentId,0D);
                //子的付款单这次的开票金额
                double subInvoiceParentSheetAmount = refPaySheetInvoiceAmount.get(uuid);

                if (Objects.equals(isCancel, 1) || Objects.equals(isDelete,BasicConstant.ONE)) {
                    //删除作废的时候子付款单这次作废删除的发票 这里删除 或 作废 已入库
                    proUpdateHelp.update(refTypePojo.getBusinessType(), corpid,parentId,refTypePojo.getInvoiceAmountAttr(),Arith.sub(historyInvoiceAmount,subInvoiceParentSheetAmount));
                } else {
                    //新增这里前面的金额明细还没有入库 所以这里直接取子的总开票金额
                    //新增时子付款单是历史所有开票金额 父现在的总开票金额 = 子历史开票金额 + 子总开票金额
                    proUpdateHelp.update(refTypePojo.getBusinessType(), corpid,parentId,refTypePojo.getInvoiceAmountAttr(),Arith.add(historyInvoiceAmount,subInvoiceParentSheetAmount));
                }
            }
        }
    }


    /**
     * 审批、新建、编辑、还原 金额判断
     *
     * @param corpid       公司id
     * @param purchaseInvoiceId    发票id
     * @param invoiceMoney 合同或回款的 开票金额
     * @param relationIdIn 合同或回款的id（新增或编辑）
     * @author yuqian
     * 单次合同开票判断开票金额小于合同可开;
     * 单次回款开票判断开票金额小于合同可开和回款可开;
     * 付款 采购合同开票金额小于采购合同可开金额,开票金额小于付款计划可开金额
     */
    @Override
    @SuppressWarnings("unchecked")
    public void invoiceAmountJudgment(String corpid, Long purchaseInvoiceId, Double invoiceMoney, Map<String, Object> relationIdIn,Integer isImport,Integer isCover,Integer isRestore,JSONArray amountDetail) throws XbbException {
       saasPurchaseInvoiceHelp.invoiceAmountJudgment(corpid, purchaseInvoiceId, invoiceMoney, relationIdIn, isImport, isCover, isRestore, amountDetail);
    }




    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        JSONArray jsonArray = new JSONArray();
        String corpid = handlerExplainInLinkItemDTO.getCorpid();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = new ArrayList<>();
        paasFormDataEntityExts.add(handlerExplainInLinkItemDTO.getPaasFormDataEntityExt());
        Map<String,List<PaasFormDataEntityExt>> paySheetMap = splitPaySheet(paasFormDataEntityExts,handlerExplainInLinkItemDTO.getCorpid());
        Map<Long,Double> purchaseIdToUnInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> refIdToUnInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        verifySingleData(xbbRefTypeEnum,handlerExplainInLinkItemDTO.getPaasFormDataEntityExt(),jsonArray, corpid,paySheetMap,purchaseIdToUnInvoiceAmountMap,refIdToUnInvoiceAmountMap);
        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        boolean isPrePaySheet = Objects.equals(linkFormData.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr()),PaySheetTypeEnum.PREPAY.getCode());
        PaasFormDataEntityExt paasFormDataEntityExt = handlerExplainInLinkItemDTO.getPaasFormDataEntityExt();
        FieldAttrEntity linkSupplierField = new FieldAttrEntity();
        FieldAttrEntity linkPurchaseField = new FieldAttrEntity();
        FieldAttrEntity linkPayPlanField = new FieldAttrEntity();
        FieldAttrEntity linkPaySheetField = new FieldAttrEntity();
        FieldAttrEntity linkPayRelationshipField = new FieldAttrEntity();
        for(FieldAttrEntity fieldAttrEntity :explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(),PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr())) {
                linkSupplierField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(),PurchaseInvoiceEnum.PURCHASE_ID.getAttr())) {
                linkPurchaseField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(),PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr())) {
                linkPayPlanField = fieldAttrEntity;
            }
            if(Objects.equals(fieldAttrEntity.getAttr(),PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr())){
                linkPaySheetField = fieldAttrEntity;
            }
            if(Objects.equals(fieldAttrEntity.getAttr(),PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr())){
                linkPayRelationshipField = fieldAttrEntity;
            }
        }
        DefaultAttrPoJo defaultAttrPoJo;
        JSONObject jsonObject;
        JSONArray linkSupplierArr;
        JSONArray linkPurchaseArr;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        switch (redundantTemplateTypeEnum) {
            case SUPPLIER:
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData,SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, supplierName));
                break;
            case PURCHASE:
                linkSupplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData,PurchaseEnum.SUPPLIER_ID.getAttr(), new JSONArray());
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkSupplierArr));
                String purchaseNo = paasFormDataEntityExt.getSerialNo();
                linkPurchaseField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId,purchaseNo));
                break;
            case PAY_PLAN:
                linkSupplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData,PayPlanEnum.LINK_SUPPLIER.getAttr(), new JSONArray());
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkSupplierArr));
                linkPurchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData,PayPlanEnum.LINK_PURCHASE.getAttr(), new JSONArray());
                linkPurchaseField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkPurchaseArr));
                String paymentNo = paasFormDataEntityExt.getSerialNo();
                linkPayPlanField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId,paymentNo));
                defaultAttrPoJo = new DefaultAttrPoJo();
                defaultAttrPoJo.setUseLinkValue(BasicConstant.ONE);
                jsonObject = new JSONObject();
                jsonObject.put("text", I18nMessageUtil.getMessage(PayRelationshipEnum.PAY_PLAN.getAlias()));
                jsonObject.put("value",PayRelationshipEnum.PAY_PLAN.getCode());
                defaultAttrPoJo.setLinkFormValue(jsonObject);
                linkPayRelationshipField.setDefaultAttr(defaultAttrPoJo);
                break;
            case PAY_SHEET:
                List<PaasFormDataEntityExt> paySheetEntityExtList = null;
                List<PaasFormDataEntityExt> addList = new ArrayList<>();
                List<PaasFormDataEntityExt> removeList = new ArrayList<>();
                List<PaasFormDataEntityExt> removeSubPaySheet = new ArrayList<>();
                if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                    if (Objects.nonNull(paasFormDataEntityExt.getUuid())) {
                        if (paySheetMap.containsKey(paasFormDataEntityExt.getUuid())) {
                            paySheetEntityExtList = paySheetMap.get(paasFormDataEntityExt.getUuid());
                        }
                        if(CollectionsUtil.isNotEmpty(paySheetEntityExtList)){
                            for(PaasFormDataEntityExt paasFormDataEntity : paySheetEntityExtList){
                                double refUnInvoiceAmount = refIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntity.getId(),0D);
                                if(refUnInvoiceAmount == BasicConstant.ZERO_DOUBLE){
                                    removeSubPaySheet.add(paasFormDataEntity);
                                }
                            }
                            if(!Objects.equals(paySheetEntityExtList.size(),removeSubPaySheet.size())){
                                paySheetEntityExtList.removeAll(removeSubPaySheet);
                            }
                            addList.addAll(paySheetEntityExtList);
                            removeList.add(paasFormDataEntityExt);
                        }
                    }
                    paasFormDataEntityExts.removeAll(removeList);
                    paasFormDataEntityExts.addAll(addList);
                }
                linkSupplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData,PaySheetEnum.LINK_SUPPLIER.getAttr(), new JSONArray());
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkSupplierArr));
                if(!isPrePaySheet) {
                    JSONArray purchaseArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData,PaySheetEnum.LINK_PURCHASE.getAttr(),new JSONArray());
                    Map<Long,Object> purchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for(int i=0;i<purchaseArray.size();i++){
                        JSONObject object = purchaseArray.getJSONObject(i);
                        purchaseMap.put(object.getLong(BasicConstant.ID),object);
                    }
                    if(CollectionsUtil.isNotEmpty(removeSubPaySheet)) {
                        for(PaasFormDataEntityExt paasFormDataEntity : removeSubPaySheet){
                            Long id = paasFormDataEntity.getData().getJSONArray(PaySheetEnum.LINK_PURCHASE.getAttr()).getLong(BasicConstant.ZERO);
                            if(purchaseMap.get(id) != null){
                              Object purchaseObject = purchaseMap.get(id);
                              purchaseArray.remove(purchaseObject);
                            }
                        }
                    }
                    linkPurchaseField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(purchaseArray));

                }
                JSONArray paySheetArr = new JSONArray();
                /*List<PaasFormDataEntityExt> paySheetEntityExts = new ArrayList<>();
                if(CollectionsUtil.isEmpty(paySheetEntityExtList)){
                    PayPlanSheetEntityExt paySheetEntityExt = new PayPlanSheetEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntityExt,paySheetEntityExt);
                    paySheetEntityExts.add(paySheetEntityExt);
                }else {
                    paySheetEntityExts.addAll(paySheetEntityExtList);
                }*/
                if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                    for (PaasFormDataEntityExt paySheetEntity : paasFormDataEntityExts) {
                        JSONObject json = new JSONObject();
                        JSONObject data = paySheetEntity.getData();
                        json.put(StringConstant.SAAS_LINK_BUSINESS_ID, paySheetEntity.getId());
                        json.put(StringConstant.SAAS_LINK_BUSINESS_NAME, paySheetEntity.getSerialNo());
                        json.put(InvoiceConstant.PAY_SHEET_TYPE, data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr()));
                        paySheetArr.add(json);
                    }
                    linkPaySheetField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(paySheetArr));
                }
                defaultAttrPoJo = new DefaultAttrPoJo();
                defaultAttrPoJo.setUseLinkValue(BasicConstant.ONE);
                jsonObject = new JSONObject();
                jsonObject.put("text",I18nMessageUtil.getMessage(PayRelationshipEnum.PAY_SHEET.getAlias()));
                jsonObject.put("value",PayRelationshipEnum.PAY_SHEET.getCode());
                defaultAttrPoJo.setLinkFormValue(jsonObject);
                linkPayRelationshipField.setDefaultAttr(defaultAttrPoJo);
                break;
            default:
                break;
        }
    }

    @Override
    public void formatBatchLinkAddExplain(HandlerExplainBatchLinkItemDTO handlerExplainBatchLinkItemDTO) throws XbbException {
        List<PaasFormDataEntityExt> paasFormDataEntityExts = handlerExplainBatchLinkItemDTO.getPaasFormDataEntityExts();
        Integer linkBusinessType = handlerExplainBatchLinkItemDTO.getLinkBusinessType();
        String corpid = handlerExplainBatchLinkItemDTO.getCorpid();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(linkBusinessType);
        JSONArray jsonArray = new JSONArray();
        Map<String,List<PaasFormDataEntityExt>> paySheetMap = splitPaySheet(paasFormDataEntityExts,handlerExplainBatchLinkItemDTO.getCorpid());
        Map<Long,Double> purchaseIdToUnInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> refIdToUnInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        verifyData(xbbRefTypeEnum, paasFormDataEntityExts, jsonArray, corpid,paySheetMap,purchaseIdToUnInvoiceAmountMap,refIdToUnInvoiceAmountMap);
        List<FieldAttrEntity> explainList = handlerExplainBatchLinkItemDTO.getExplainList();
        FieldAttrEntity linkSupplierField = new FieldAttrEntity();
        FieldAttrEntity linkPurchaseField = new FieldAttrEntity();
        FieldAttrEntity linkPayPlanField = new FieldAttrEntity();
        FieldAttrEntity linkPaySheetField = new FieldAttrEntity();
        FieldAttrEntity linkPayRelationshipField = new FieldAttrEntity();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr())) {
                linkSupplierField = fieldAttrEntity;
            }
            if (Objects.equals(attr, PurchaseInvoiceEnum.PURCHASE_ID.getAttr())) {
                linkPurchaseField = fieldAttrEntity;
            }
            if (Objects.equals(attr, PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr())) {
                linkPayPlanField = fieldAttrEntity;
            }
            if(Objects.equals(attr,PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr())){
                linkPaySheetField = fieldAttrEntity;
            }
            if(Objects.equals(attr,PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr())){
                linkPayRelationshipField = fieldAttrEntity;
            }
        }

        JSONArray supplierArr = new JSONArray();
        JSONArray purchaseArr = new JSONArray();
        JSONArray payPlanArr = new JSONArray();
        JSONArray paySheetArr = new JSONArray();
        Set<JSONObject> copyPurchase = new HashSet<>();
        JSONObject jsonObject;
        DefaultAttrPoJo defaultAttrPoJo;
        switch (xbbRefTypeEnum) {
            case PURCHASE:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data,PurchaseEnum.SUPPLIER_ID.getAttr(), jsonArray);
                    JSONObject purchaseObj = new JSONObject();
                    purchaseObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, paasFormDataEntityExt.getId());
                    purchaseObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, paasFormDataEntityExt.getSerialNo());
                    purchaseArr.add(purchaseObj);
                }
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(supplierArr));
                linkPurchaseField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(purchaseArr));
                break;
            case PAY_PLAN:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PayPlanEnum.LINK_SUPPLIER.getAttr(), jsonArray);
                    purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PayPlanEnum.LINK_PURCHASE.getAttr(), jsonArray);
                    if(CollectionsUtil.isNotEmpty(purchaseArr)) {
                        copyPurchase.add(purchaseArr.getJSONObject(0));
                    }
                    JSONObject payPlanObj = new JSONObject();
                    payPlanObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, paasFormDataEntityExt.getId());
                    payPlanObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, paasFormDataEntityExt.getSerialNo());
                    payPlanArr.add(payPlanObj);
                }
                purchaseArr.clear();
                purchaseArr.addAll(copyPurchase);
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(supplierArr));
                linkPurchaseField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(purchaseArr));
                linkPayPlanField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(payPlanArr));
                defaultAttrPoJo = new DefaultAttrPoJo();
                defaultAttrPoJo.setUseLinkValue(BasicConstant.ONE);
                jsonObject = new JSONObject();
                jsonObject.put("text",I18nMessageUtil.getMessage(PayRelationshipEnum.PAY_PLAN.getAlias()));
                jsonObject.put("value",PayRelationshipEnum.PAY_PLAN.getCode());
                defaultAttrPoJo.setLinkFormValue(jsonObject);
                linkPayRelationshipField.setDefaultAttr(defaultAttrPoJo);
                break;
            case PAY_SHEET:
                List<PaasFormDataEntityExt> removeSubPaySheet = new ArrayList<>();
                List<PaasFormDataEntityExt> addList = new ArrayList<>();
                List<PaasFormDataEntityExt> removeList = new ArrayList<>();
                if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)) {
                    for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                        double refUnInvoiceAmount = refIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(), 0D);
                        if (refUnInvoiceAmount == BasicConstant.ZERO_DOUBLE) {
                            removeSubPaySheet.add(paasFormDataEntityExt);
                        }
                    }
                    for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                        if (Objects.nonNull(paasFormDataEntityExt.getUuid())) {
                            if (paySheetMap.containsKey(paasFormDataEntityExt.getUuid())) {
                                List<PaasFormDataEntityExt> paySheetEntityExtList = paySheetMap.get(paasFormDataEntityExt.getUuid());
                                addList.addAll(paySheetEntityExtList);
                                removeList.add(paasFormDataEntityExt);
                            }
                        }
                    }
                }
                paasFormDataEntityExts.removeAll(removeList);
                paasFormDataEntityExts.addAll(addList);
                if (removeSubPaySheet.size() > BasicConstant.ZERO) {
                    paasFormDataEntityExts.removeAll(removeSubPaySheet);
                }

                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    if(data.get(PaySheetEnum.LINK_SUPPLIER.getAttr()) instanceof  String){
                        supplierArr.clear();
                        JSONObject object = new JSONObject();
                        object.put(BasicConstant.ID,FastJsonHelper.getLongOrDefaultFromFormData(data,PaySheetEnum.LINK_SUPPLIER.getAttr(),0L));
                        object.put(BasicConstant.NAME,FastJsonHelper.getStringOrDefaultFromFormData(data,PaySheetEnum.SUPPLIER_LINK_TEXT.getAttr(),""));
                        supplierArr.add(object);
                    }else {
                        supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PaySheetEnum.LINK_SUPPLIER.getAttr(), jsonArray);
                    }
                        purchaseArr = data.getJSONArray(PaySheetEnum.LINK_PURCHASE.getAttr());
                    JSONObject paySheetObj = new JSONObject();
                    paySheetObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, paasFormDataEntityExt.getId());
                    paySheetObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, paasFormDataEntityExt.getSerialNo());
                    paySheetObj.put(InvoiceConstant.PAY_SHEET_TYPE, data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr()));
                    paySheetArr.add(paySheetObj);
                    if(CollectionsUtil.isNotEmpty(purchaseArr)){
                        Long purchaseRefId = 0L;
                        if (purchaseArr.get(0) instanceof JSONObject) {
                            purchaseRefId = purchaseArr.getJSONObject(0).getLong(BasicConstant.ID);
                            String purchaseName = purchaseArr.getJSONObject(0).getString(BasicConstant.NAME);
                            JSONObject json = new JSONObject();
                            json.put(BasicConstant.ID,purchaseRefId);
                            json.put(BasicConstant.NAME,purchaseName);
                            copyPurchase.add(json);
                        } else {
                            purchaseRefId = data.getJSONArray(PaySheetEnum.LINK_PURCHASE.getAttr()).getLong(0);
                            String purchaseName = data.getJSONArray(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr()).getString(0);
                            JSONObject json = new JSONObject();
                            json.put(BasicConstant.ID,purchaseRefId);
                            json.put(BasicConstant.NAME,purchaseName);
                            copyPurchase.add(json);
                        }
                        purchaseArr.clear();
                        purchaseArr.addAll(copyPurchase);
                        linkPurchaseField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(purchaseArr));
                    }
                }
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(supplierArr));
                linkPaySheetField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(paySheetArr));
                defaultAttrPoJo = new DefaultAttrPoJo();
                defaultAttrPoJo.setUseLinkValue(BasicConstant.ONE);
                jsonObject = new JSONObject();
                jsonObject.put("text",I18nMessageUtil.getMessage(PayRelationshipEnum.PAY_SHEET.getAlias()));
                jsonObject.put("value",PayRelationshipEnum.PAY_SHEET.getCode());
                defaultAttrPoJo.setLinkFormValue(jsonObject);
                linkPayRelationshipField.setDefaultAttr(defaultAttrPoJo);
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
    }

    @Override
    public void batchEditAttr(PurchaseInvoiceEditAttrUpdateDTO purchaseInvoiceEditAttrUpdateDTO) throws XbbException {
        try {
            List<PurchaseInvoiceUpdateDTO> purchaseInvoiceList = new ArrayList<>();
            purchaseInvoiceEditAttrUpdateDTO.getDataIdList().forEach((item)->{
                PurchaseInvoiceUpdateDTO purchaseInvoiceUpdateDTO = new PurchaseInvoiceUpdateDTO();
                purchaseInvoiceUpdateDTO.setId(item);
                JSONObject data = ProSaveHelp.getBatchUpdateData(purchaseInvoiceEditAttrUpdateDTO.getFieldEditedList());
                purchaseInvoiceUpdateDTO.setData(data);
                purchaseInvoiceList.add(purchaseInvoiceUpdateDTO);
            });
            List<PurchaseInvoiceEntityExt> purchaseInvoiceEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (!purchaseInvoiceList.isEmpty()) {
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", purchaseInvoiceEditAttrUpdateDTO.getCorpid());
                param.put("idIn", purchaseInvoiceEditAttrUpdateDTO.getDataIdList());
                purchaseInvoiceEntityList = purchaseInvoiceModel.findEntitys(param);
                if (Objects.isNull(purchaseInvoiceEntityList)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }

                PurchaseInvoiceUpdateBatchDTO purchaseInvoiceUpdateBatchDTO = new PurchaseInvoiceUpdateBatchDTO();
                BeanUtil.copyProperties(purchaseInvoiceEditAttrUpdateDTO, purchaseInvoiceUpdateBatchDTO);
                purchaseInvoiceUpdateBatchDTO.setInvoiceList(purchaseInvoiceList);
                updateBatch(purchaseInvoiceUpdateBatchDTO);
            }

            // 批量编辑日志
            List<String> updataItemList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PurchaseInvoiceEntityExt item : purchaseInvoiceEntityList) {
                dataIdList.add(item.getId());
                String serialNo = item.getSerialNo();
                updataItemList.add(serialNo);
            }
            String updataItem = StringUtils.join(updataItemList, "，");
            String userId = purchaseInvoiceEditAttrUpdateDTO.getUserId();
            String corpid = purchaseInvoiceEditAttrUpdateDTO.getCorpid();
            String loginUserName = purchaseInvoiceEditAttrUpdateDTO.getLoginUserName();
            // 标签特殊处理
            Integer fieldType = purchaseInvoiceEditAttrUpdateDTO.getFieldType();
            Boolean isFieldDependence = purchaseInvoiceEditAttrUpdateDTO.getIsFieldDependence();
            logHelp.analysisLabel(corpid, fieldType, isFieldDependence,purchaseInvoiceEditAttrUpdateDTO.getLogFieldEditedList());

            String changedLogItemsStr = logHandleHelp.getChangedLogItemsStr(purchaseInvoiceEditAttrUpdateDTO.getLogFieldEditedList());
            if(dataIdList.size() > 1 ){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, XbbRefTypeEnum.PURCHASE_INVOICE.getName(),
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(XbbRefTypeEnum.PURCHASE_INVOICE.getName());
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.PURCHASE_INVOICE, OperateTypeEnum.EDIT,
                        "", "", memo, purchaseInvoiceEditAttrUpdateDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, XbbRefTypeEnum.PURCHASE_INVOICE.getName(), updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.PURCHASE_INVOICE, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, purchaseInvoiceEditAttrUpdateDTO.getHttpHeader());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("invoiceService.batchEditAttr 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 校验合并开票是否符合要求
     *
     * @param xbbRefTypeEnum 类型
     * @param paasFormDataEntityExts 实体
     * @param jsonArray 数组
     * @param corpid 公司ID
     * @throws XbbException 异常
     */
    private void verifyData(XbbRefTypeEnum xbbRefTypeEnum, List<PaasFormDataEntityExt> paasFormDataEntityExts, JSONArray jsonArray, String corpid,Map<String,List<PaasFormDataEntityExt>> paySheetMap,Map<Long,Double> purchaseIdToUnInvoiceAmountMap,Map<Long,Double> refIdToUnInvoiceAmountMap) throws XbbException{
        Long lastSupplierId = null;
        Double unInvoiceAmount = 0D;
        getPurchaseIdToInvoiceAmountMap(xbbRefTypeEnum, paasFormDataEntityExts, corpid,purchaseIdToUnInvoiceAmountMap,refIdToUnInvoiceAmountMap,paySheetMap);
        switch (xbbRefTypeEnum) {
            case PURCHASE:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject dataList = paasFormDataEntityExt.getData();
                    JSONArray supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList,PurchaseEnum.SUPPLIER_ID.getAttr(), jsonArray);
                    if (supplierArr.isEmpty()) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                    }
                    Long supplierId = supplierArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                    if (Objects.isNull(supplierId) || Objects.equals(supplierId, 0L)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                    }
                    if (Objects.nonNull(lastSupplierId) && !Objects.equals(lastSupplierId, supplierId)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_INVOICE_MUST_SAME_SUPPLIER);
                    }
                    unInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                    if (unInvoiceAmount <= BasicConstant.ZERO_DOUBLE) {
                        throw new XbbException(InvoiceErrorCodeEnum.APT_ERROR_216001, ErrorMessageConstant.PURCHASE_BATCH_ZERO_AMOUNT);
                    }
                    lastSupplierId = supplierId;
                }
                break;
            case PAY_PLAN:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject dataList = paasFormDataEntityExt.getData();
                    String status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());
                    boolean isBad = Objects.equals(status, PayPlanStatusEnum.BAD_DEBT.getCode()) || Objects.equals(status, PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode());
                    if (isBad) {
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216017);
                    }
                    JSONArray supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PayPlanEnum.LINK_SUPPLIER.getAttr(), jsonArray);
                    JSONArray purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PayPlanEnum.LINK_PURCHASE.getAttr(), jsonArray);
                    if (purchaseArr.isEmpty()) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                    }
                    Long purchaseId = purchaseArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                    if (Objects.isNull(purchaseId) || Objects.equals(purchaseId, 0L)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_PLAN_LINK_PURCHASE);
                    }
                    Double purchaseUnInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(purchaseId,0D);
                    if (Objects.equals(purchaseUnInvoiceAmount,BasicConstant.ZERO_DOUBLE)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_BATCH_ZERO_AMOUNT);
                    }
                    Long supplierId = supplierArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                    if (Objects.nonNull(lastSupplierId) && !Objects.equals(lastSupplierId, supplierId)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAYPLAN_INVOICE_MUST_SAME_SUPPLIER);
                    }
                    unInvoiceAmount = refIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                    if (unInvoiceAmount <= BasicConstant.ZERO_DOUBLE) {
                        throw new XbbException(InvoiceErrorCodeEnum.APT_ERROR_216002, ErrorMessageConstant.PAYPLAN_BATCH_ZERO_AMOUNT);
                    }
                    lastSupplierId = supplierId;
                }
                break;
            case PAY_SHEET:
                int size = paasFormDataEntityExts.size();
                int isPrePaySheetSize = 0;
                boolean hasPrePaySheet = false;
                for(int i = 0;i < paasFormDataEntityExts.size();i++){
                    PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataEntityExts.get(i);
                    JSONObject dataList = paasFormDataEntityExt.getData();
                    String status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                    boolean isBad = PaySheetTypeEnum.isBad(status);
                    boolean isRed = PaySheetTypeEnum.isRed(status);
                    boolean isWriteOffPrePaySheet= Objects.equals(status,PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode());
                    boolean isPrePaymentSheet = Objects.equals(status,PaySheetTypeEnum.PREPAY.getCode());
                    if(isRed || isBad){
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216017);
                    }
                    if(isWriteOffPrePaySheet){
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217021);
                    }
                    if(isPrePaymentSheet){
                        hasPrePaySheet = true;
                        isPrePaySheetSize++;
                    }
                    if(Objects.equals(i,size-1)){
                        if(hasPrePaySheet) {
                            if (isPrePaySheetSize != size) {
                                throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217022);
                            }
                        }
                    }
                    JSONArray supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PaySheetEnum.LINK_SUPPLIER.getAttr(), jsonArray);
                    if(!isPrePaymentSheet) {
                        JSONArray purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PaySheetEnum.LINK_PURCHASE.getAttr(), jsonArray);
                        checkPaySheetRefPurchaseInvoiceAmount(purchaseArr,purchaseIdToUnInvoiceAmountMap,true);
                        /*if (purchaseArr.isEmpty()) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                        }
                        Long purchaseId = purchaseArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                        if (Objects.isNull(purchaseId) || Objects.equals(purchaseId, 0L)) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_LINK_PURCHASE);
                        }
                        Double purchaseUnInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(purchaseId, 0D);
                        if (Objects.equals(purchaseUnInvoiceAmount, BasicConstant.ZERO_DOUBLE)) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_BATCH_ZERO_AMOUNT);
                        }*/
                    }
                    Long supplierId = supplierArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                    if (Objects.nonNull(lastSupplierId) && !Objects.equals(lastSupplierId, supplierId)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_INVOICE_MUST_SAME_SUPPLIER);
                    }
                    if(Objects.equals(paasFormDataEntityExt.getAlone(),SheetAloneEnum.PARENT.getCode())){
                        if(paySheetMap.containsKey(paasFormDataEntityExt.getUuid())){
                            List<PaasFormDataEntityExt> paasFormDataEntityExtList = paySheetMap.get(paasFormDataEntityExt.getUuid());
                            if(CollectionsUtil.isNotEmpty(paasFormDataEntityExtList)) {
                                for (PaasFormDataEntityExt paasFormData : paasFormDataEntityExtList) {
                                    unInvoiceAmount =  Arith.add(unInvoiceAmount, refIdToUnInvoiceAmountMap.getOrDefault(paasFormData.getId(), 0D));
                                }
                            }
                        }
                    }else {
                        unInvoiceAmount = refIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                    }
                    if (unInvoiceAmount <= BasicConstant.ZERO_DOUBLE) {
                        throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216022, ErrorMessageConstant.PAYSHEET_BATCH_ZERO_AMOUNT);
                    }
                    lastSupplierId = supplierId;
                }
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
    }

    private void checkPaySheetRefPurchaseInvoiceAmount(JSONArray purchaseArr,Map<Long,Double> purchaseIdToUnInvoiceAmountMap,boolean isMerge) throws XbbException{
        if(CollectionsUtil.isNotEmpty(purchaseArr)){
           Integer invoiceZero = 0;
            for(int i=0;i<purchaseArr.size();i++){
                Long purchaseId = purchaseArr.getJSONObject(i).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                if (Objects.isNull(purchaseId) || Objects.equals(purchaseId, 0L)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_LINK_PURCHASE);
                }
                Double purchaseUnInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(purchaseId, 0D);
                if (Objects.equals(purchaseUnInvoiceAmount, BasicConstant.ZERO_DOUBLE)) {
                    invoiceZero ++;
                }
            }
            if(Objects.equals(invoiceZero,purchaseArr.size())){
                if(isMerge) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_BATCH_ZERO_AMOUNT);
                }else {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_SINGLE_ZERO_AMOUNT);
                }
            }
        }else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_LINK_PURCHASE);
        }
    }

    private Map<String,List<PaasFormDataEntityExt>> splitPaySheet(List<PaasFormDataEntityExt> paasFormDataEntityExtList,String corpid) throws XbbException{
        Set<String> uuidList = new HashSet<>();
        Map<String,List<PaasFormDataEntityExt>> paySheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaasFormDataEntityExt> subPaySheetList = new ArrayList<>();
        paasFormDataEntityExtList.forEach(paasFormDataEntityExt -> {
            if (StringUtil.isNotEmpty(paasFormDataEntityExt.getUuid())) {
                uuidList.add(paasFormDataEntityExt.getUuid());
            }
        });
        if(CollectionsUtil.isNotEmpty(uuidList)) {
            subPaySheetList = fundHelp.getChildEsDataListByParentUuids(XbbRefTypeEnum.PAY_SHEET, corpid, uuidList, null, null);
        }
        subPaySheetList.forEach(subPaasFormDataEntityExt -> {
            List<PaasFormDataEntityExt> paySheetList = new ArrayList<>();
            if(paySheetMap.containsKey(subPaasFormDataEntityExt.getUuid())){
                paySheetMap.get(subPaasFormDataEntityExt.getUuid()).add(subPaasFormDataEntityExt);
            }else {
                paySheetList.add(subPaasFormDataEntityExt);
                paySheetMap.put(subPaasFormDataEntityExt.getUuid(),paySheetList);
            }
        });
        return paySheetMap;
    }

    /**
     * 校验单个开票是否符合要求
     *
     * @param xbbRefTypeEnum 类型
     * @param paasFormDataEntityExt 实体
     * @param jsonArray 数组
     * @param corpid 公司ID
     * @throws XbbException 异常
     */
    private void verifySingleData(XbbRefTypeEnum xbbRefTypeEnum, PaasFormDataEntityExt paasFormDataEntityExt, JSONArray jsonArray, String corpid,Map<String,List<PaasFormDataEntityExt>> paySheetMap,Map<Long,Double> purchaseIdToUnInvoiceAmountMap,Map<Long,Double> refIdToUnInvoiceAmountMap) throws XbbException{
        JSONObject data;
        JSONArray supplierArr;
        JSONArray purchaseArr;
        String status;
        Long purchaseId;
        Long supplierId;
        Double unInvoiceAmount = 0D;
        Double purchaseUnInvoiceAmount = 0D;
        getPurchaseIdToInvoiceAmountMap(xbbRefTypeEnum,Collections.singletonList(paasFormDataEntityExt), corpid,purchaseIdToUnInvoiceAmountMap,refIdToUnInvoiceAmountMap,paySheetMap);
        switch (xbbRefTypeEnum) {
            case PURCHASE:
                data = paasFormDataEntityExt.getData();
                supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PurchaseEnum.SUPPLIER_ID.getAttr(), jsonArray);
                if (supplierArr.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                }
                supplierId = supplierArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                if (Objects.isNull(supplierId) || Objects.equals(supplierId, 0L)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                }
                unInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                if (unInvoiceAmount <= BasicConstant.ZERO_DOUBLE) {
                    throw new XbbException(InvoiceErrorCodeEnum.APT_ERROR_216001, ErrorMessageConstant.PURCHASE_SINGLE_ZERO_AMOUNT);
                }
                break;
            case PAY_PLAN:
                data = paasFormDataEntityExt.getData();
                status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());
                boolean isBad = Objects.equals(status, PayPlanStatusEnum.BAD_DEBT.getCode()) || Objects.equals(status, PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode());
                if (isBad) {
                    throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216017);
                }
                supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PayPlanEnum.LINK_SUPPLIER.getAttr(), jsonArray);
                if(supplierArr.isEmpty()){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_PLAN_LINK_SUPPLIER);
                }
                purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PayPlanEnum.LINK_PURCHASE.getAttr(), jsonArray);
                if (purchaseArr.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_PLAN_LINK_PURCHASE);
                }
                purchaseId = purchaseArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                if (Objects.isNull(purchaseId) || Objects.equals(purchaseId, 0L)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_PLAN_LINK_PURCHASE);
                }
                purchaseUnInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(purchaseId,0D);
                if (purchaseUnInvoiceAmount <= BasicConstant.ZERO_DOUBLE){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_SINGLE_ZERO_AMOUNT);
                }
                unInvoiceAmount = refIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                if (unInvoiceAmount <= BasicConstant.ZERO_DOUBLE) {
                    throw new XbbException(InvoiceErrorCodeEnum.APT_ERROR_216002, ErrorMessageConstant.PAY_PLAN_SINGLE_ZERO_AMOUNT);
                }
                break;
            case PAY_SHEET:
                data = paasFormDataEntityExt.getData();
                status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                boolean isBadType = PaySheetTypeEnum.isBad(status);
                boolean isRedType = PaySheetTypeEnum.isRed(status);
                boolean isPrePaySheet = Objects.equals(status,PaySheetTypeEnum.PREPAY.getCode()) || Objects.equals(status,PaySheetTypeEnum.RED_PREPAY.getCode());
                boolean isWriteOffPrePaySheet= Objects.equals(status,PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode());
                if(isBadType || isRedType){
                    throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216017);
                }
                if(isWriteOffPrePaySheet){
                    throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217021);
                }
                supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PaySheetEnum.LINK_SUPPLIER.getAttr(), jsonArray);
                if(supplierArr.isEmpty()){
                    if(isPrePaySheet){
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_LINK_SUPPLIER);
                    }else {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                    }
                }
                if(!isPrePaySheet){
                    purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, PaySheetEnum.LINK_PURCHASE.getAttr(), jsonArray);
                    checkPaySheetRefPurchaseInvoiceAmount(purchaseArr,purchaseIdToUnInvoiceAmountMap,false);
                    /*purchaseId = purchaseArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                    if (Objects.isNull(purchaseId) || Objects.equals(purchaseId, 0L)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_LINK_PURCHASE);
                    }
                    purchaseUnInvoiceAmount = purchaseIdToUnInvoiceAmountMap.getOrDefault(purchaseId,0D);
                    if (purchaseUnInvoiceAmount <= BasicConstant.ZERO_DOUBLE) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_SINGLE_ZERO_AMOUNT);
                    }*/
                }
                if(Objects.equals(paasFormDataEntityExt.getAlone(),SheetAloneEnum.PARENT.getCode())){
                    if(paySheetMap.containsKey(paasFormDataEntityExt.getUuid())){
                        List<PaasFormDataEntityExt> paasFormDataEntityExtList = paySheetMap.get(paasFormDataEntityExt.getUuid());
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityExtList)) {
                            for (PaasFormDataEntityExt paasFormData : paasFormDataEntityExtList) {
                                unInvoiceAmount =  Arith.add(unInvoiceAmount, refIdToUnInvoiceAmountMap.getOrDefault(paasFormData.getId(), 0D));
                            }
                        }
                    }
                }else {
                    unInvoiceAmount = refIdToUnInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                }
                if (unInvoiceAmount <= BasicConstant.ZERO_DOUBLE){
                    throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216022, ErrorMessageConstant.PAY_SHEET_SINGLE_ZERO_AMOUNT);
                }
                break;
            default:
                return;
        }
    }

    /*private Map<Long, Double> getPurchaseIdToInvoiceAmountMap(XbbRefTypeEnum xbbRefTypeEnum, PaasFormDataEntityExt paasFormDataEntityExt, String corpid) throws XbbException {
        List<PaasFormDataEntityExt> paasFormDataEntityExts = Collections.singletonList(paasFormDataEntityExt);
        return getPurchaseIdToInvoiceAmountMap(xbbRefTypeEnum, paasFormDataEntityExts, corpid);
    }*/
    /**
     * 获取合同ID和合同未开票金额对应关系
     *
     * @param xbbRefTypeEnum         业务类型
     * @param paasFormDataEntityExts 实体集合
     * @param corpid                 公司ID
     * @author zhouwq
     * @date 2020/1/8 19:24
     */
    private void getPurchaseIdToInvoiceAmountMap(XbbRefTypeEnum xbbRefTypeEnum, List<PaasFormDataEntityExt> paasFormDataEntityExts, String corpid,Map<Long,Double> purchaseIdToUnInvoiceAmountMap,Map<Long,Double> refIdToUnInvoiceAmountMap,Map<String,List<PaasFormDataEntityExt>> paySheetMap) throws XbbException {
        Set<Long> purchaseIds = new HashSet<>();
        Set<Long> refIds = new HashSet<>();
        List<PaasFormDataEntityExt> paasFormDataEntityList =  new ArrayList<>();
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.CORPID, corpid);
        map.put("del",BasicConstant.ZERO);
        map.put("isCancel",BasicConstant.ZERO);
        switch (xbbRefTypeEnum) {
            case PURCHASE:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    purchaseIds.add(paasFormDataEntityExt.getId());
                }
                break;
            case PAY_PLAN:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject dataList = paasFormDataEntityExt.getData();
                    JSONArray purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PayPlanEnum.LINK_PURCHASE.getAttr(), new JSONArray());
                    if (purchaseArr.isEmpty()) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PURCHASE_LINK_SUPPLIER);
                    }
                    Long purchaseId = purchaseArr.getJSONObject(BasicConstant.ZERO).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                    purchaseIds.add(purchaseId);
                    refIds.add(paasFormDataEntityExt.getId());
                }
                map.put("payPlan",refIds);
                break;
            case PAY_SHEET:
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                    JSONObject dataList = paasFormDataEntityExt.getData();
                    String status = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                    boolean isPrePaymentSheet = Objects.equals(status,PaySheetTypeEnum.PREPAY.getCode()) || Objects.equals(status,PaySheetTypeEnum.RED_PREPAY.getCode());
                    if(!isPrePaymentSheet){
                        JSONArray purchaseArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PaySheetEnum.LINK_PURCHASE.getAttr(), new JSONArray());
                        if (purchaseArr.isEmpty()) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.PAY_SHEET_LINK_PURCHASE);
                        }
                        for(int i = 0;i<purchaseArr.size();i++){
                            Long purchaseId = purchaseArr.getJSONObject(i).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                            purchaseIds.add(purchaseId);
                        }
                        if(Objects.equals(paasFormDataEntityExt.getAlone(),SheetAloneEnum.PARENT.getCode())){
                            if(paySheetMap.containsKey(paasFormDataEntityExt.getUuid())){
                                List<PaasFormDataEntityExt> subPaasFormDataEntityList = paySheetMap.get(paasFormDataEntityExt.getUuid());
                                subPaasFormDataEntityList.forEach(item -> refIds.add(item.getId()));
                                paasFormDataEntityList.addAll(subPaasFormDataEntityList);
                            }else {
                                //容错
                                refIds.add(paasFormDataEntityExt.getId());
                                paasFormDataEntityList.add(paasFormDataEntityExt);
                            }
                        }else {
                            refIds.add(paasFormDataEntityExt.getId());
                            paasFormDataEntityList.add(paasFormDataEntityExt);
                        }
                    }else {
                        refIds.add(paasFormDataEntityExt.getId());
                        paasFormDataEntityList.add(paasFormDataEntityExt);
                    }
                }
                map.put("paySheetIdIn",refIds);
                if(CollectionsUtil.isNotEmpty(paasFormDataEntityList)) {
                    paasFormDataEntityExts = paasFormDataEntityList;
                }
                break;
            default:
                return;
        }
        List<PaasFormDataEntityExt> paasFormList = null;
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        if(!Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PURCHASE)) {
            params.put(StringConstant.IDIN, purchaseIds);
            List<PurchaseEntityExt> purchases = purchaseModel.findEntitys(params);
            paasFormList = JSONArray.parseArray(JSONArray.toJSONString(purchases),PaasFormDataEntityExt.class);
        }else {
            paasFormList = paasFormDataEntityExts;
        }
        params.remove(StringConstant.IDIN);
        params.put("purchaseIdIn", purchaseIds);
        params.put("del",BasicConstant.ZERO);
        params.put("isCancel",BasicConstant.ZERO);
        List<PurchaseInvoiceRelationshipEntity> relationshipEntityList = purchaseInvoiceRelationshipModel.findEntitys(params);
        Map<Long, Double> purchaseInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, Double> refInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(CollectionsUtil.isNotEmpty(relationshipEntityList)){
            for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : relationshipEntityList){
                saasSaveHelp.addMapNormal(purchaseInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseInvoiceRelationshipEntity.getMoney());
            }
        }
        if(CollectionsUtil.isNotEmpty(paasFormList)){
            for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormList){
                JSONObject data = paasFormDataEntityExt.getData();
                if (data != null) {
                    double amount = data.getDouble(PurchaseEnum.TOTAL_MONEY.getAttr());
                    double invoiceAmount = purchaseInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                    purchaseIdToUnInvoiceAmountMap.put(paasFormDataEntityExt.getId(),Arith.sub(amount,invoiceAmount));
                }
            }
        }
        if(!Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PURCHASE)) {
            List<PurchaseInvoiceRelationshipEntity> relationshipList = purchaseInvoiceRelationshipModel.findEntitys(map);
            if(CollectionsUtil.isNotEmpty(relationshipList)){
                for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : relationshipList){
                    if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
                        saasSaveHelp.addMapNormal(refInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPayPlanId(),purchaseInvoiceRelationshipEntity.getMoney());
                    }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                        saasSaveHelp.addMapNormal(refInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPaySheetId(),purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
            }
        }
        if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)){
            for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts){
                JSONObject data = paasFormDataEntityExt.getData();
                if (data != null) {
                    double amount = 0D;
                    if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
                        amount = data.getDouble(PayPlanEnum.AMOUNT.getAttr());
                    }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                        String status = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                        if(Objects.equals(status,PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode())){
                            //只有预付款核销的是取核销金额
                            amount = data.getDouble(PaySheetEnum.WRITE_OFF_AMOUNT.getAttr());
                        }else {
                            amount = data.getDouble(PaySheetEnum.AMOUNT.getAttr());
                        }
                    }
                    double invoiceAmount = refInvoiceAmountMap.getOrDefault(paasFormDataEntityExt.getId(),0D);
                    refIdToUnInvoiceAmountMap.put(paasFormDataEntityExt.getId(),Arith.sub(amount,invoiceAmount));
                }
            }
        }
    }

   /* private Map<String,List<PaasFormDataEntityExt>> splitPaySheet(List<PaasFormDataEntityExt> paasFormDataEntityExtList,String corpid) throws XbbException{
        Set<String> uuidList = new HashSet<>();
        Map<String,List<PaasFormDataEntityExt>> paySheetMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaasFormDataEntityExt> subPaySheetList = new ArrayList<>();
        paasFormDataEntityExtList.forEach(paasFormDataEntityExt -> {
            if (StringUtil.isNotEmpty(paasFormDataEntityExt.getUuid())) {
                uuidList.add(paasFormDataEntityExt.getUuid());
            }
        });
        if(CollectionsUtil.isNotEmpty(uuidList)) {
            subPaySheetList = fundHelp.getChildEsDataListByParentUuids(XbbRefTypeEnum.PAY_SHEET, corpid, uuidList, null, null);
        }
        subPaySheetList.forEach(subPaasFormDataEntityExt -> {
            List<PaasFormDataEntityExt> paySheetList = new ArrayList<>();
            if(paySheetMap.containsKey(subPaasFormDataEntityExt.getUuid())){
                paySheetMap.get(subPaasFormDataEntityExt.getUuid()).add(subPaasFormDataEntityExt);
            }else {
                paySheetList.add(subPaasFormDataEntityExt);
                paySheetMap.put(subPaasFormDataEntityExt.getUuid(),paySheetList);
            }
        });
        return paySheetMap;
    }*/

    @Override
    public ListAppVO formatInvoiceAppList(FormDataListDTO formDataListDTO, List<PaasFormDataEntityExt> esEntities, Integer totalCount) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        // TODO long.rao 目前列表页靠这个字段来判断发票状态0为正常，1为红冲，2为作废
        Integer statusFilter = formDataListDTO.getStatusFilter();

        for(PaasFormDataEntityExt entity : esEntities){
            Long purchaseInvoiceId = entity.getDataId();
            JSONObject data = entity.getData();
            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();
            // 其他
            if(Objects.equals(statusFilter, 1)){
                others.put("isRed", BasicConstant.ONE);
            }
            commonHelp.setPurchaseInfo(data, superScript, others);

            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            if (titleList.isEmpty()) {
                titleList.add(commonHelp.setTitle(entity.getSerialNo()));
            }

            appListPojos.add(new AppListPojo(purchaseInvoiceId, titleList, summaryList, superScript, lablesList, others, entity.getAppId(), entity.getMenuId(), entity.getFormId()));
        }
        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount(totalCount);
        return  listAppVO;
    }
    
    /**
     * 发票关联的业务数据如果删除需要先判断一下是否有发票
     * @param idList
     * @param xbbRefTypeEnum
     */
    @Override
    public void checkBusinessDeleteHaveInvoice(List<Long> idList, String corpid, XbbRefTypeEnum xbbRefTypeEnum, Collection<String> errorTypeSet, Collection<String> errorDataSet, Collection<Long> delIdList, Collection<String> delNoList,Map<String,Long> parentMap,Map<Long,String> parentSerialNoMap,Map<Long,String> subMap,Map<String,List<Long>> uuidSubMap,Map<String,List<String>> uuidSerialNoMap){
        if ( CollectionsUtil.isEmpty(idList) ) {
            return;
        }
        //判断这些回款单下面是否存在发票
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        String noneDelMsg = "";
        if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
            param.put("paySheetIdIn",idList);
            noneDelMsg = I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PAY_SHEET_INVOICE_NOT_DEL);
        }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
            param.put("payIdIn",idList);
            noneDelMsg = I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PAY_PLAN_INVOICE_NOT_DEL);
        }else{
            return;
        }
        param.put("corpid",corpid);
        param.put("del",BasicConstant.ZERO);
        List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntityList = purchaseInvoiceRelationshipModel.findEntitys(param);
        Set<Long> refIdSet = new HashSet<>();
        Set<String> refSerialNoSet = new HashSet<>();
        //根据idList 所有会删除的回款单计划去查询是否有存在发票,只要回款单存在发票,其他子回款单也不允许删除
        if( CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntityList)) {
            purchaseInvoiceRelationshipEntityList.forEach(purchaseInvoiceRelationshipEntity -> {
                if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_SHEET)){
                    if(parentSerialNoMap.containsKey(purchaseInvoiceRelationshipEntity.getPaySheetId())){
                        refIdSet.add(purchaseInvoiceRelationshipEntity.getPaySheetId());
                        refSerialNoSet.add(purchaseInvoiceRelationshipEntity.getPaySheetNo());
                    }else {
                        String uuid = subMap.getOrDefault(purchaseInvoiceRelationshipEntity.getPaySheetId(),"");
                        //放入其他子回款单
                        List<Long> allSubId =uuidSubMap.getOrDefault(uuid, new ArrayList<>());
                        List<String> allSubSerialNo = uuidSerialNoMap.getOrDefault(uuid, new ArrayList<>());
                        refIdSet.addAll(allSubId);
                        refSerialNoSet.addAll(allSubSerialNo);
                        Long parentId = parentMap.getOrDefault(uuid,0L);
                        String parentSerialNo = parentSerialNoMap.getOrDefault(parentId,"");
                        refIdSet.add(parentId);
                        refSerialNoSet.add(parentSerialNo);
                    }
                }else if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PAY_PLAN)){
                    refIdSet.add(purchaseInvoiceRelationshipEntity.getPayPlanId());
                    refSerialNoSet.add(purchaseInvoiceRelationshipEntity.getPayPlanNo());
                }
            });
            commonHelp.removeInvoiceRefNoneDel(noneDelMsg, refIdSet, refSerialNoSet, errorTypeSet, errorDataSet, delIdList, delNoList, idList);
        }
    }

    /**
     * 发票编辑时新增删除数据
     *  老的数据减去新的数据得到删除的关联数据,新的减去老的得到新增的关联数据
     * @param newData
     * @param oldData
     * @param corpid
     * @param invoiceId
     * @return
     * @throws XbbException
     */
    private InvoiceRelationshipEditPojo getAddOrDeleteRelationship(JSONObject newData, JSONObject oldData,String corpid,Long invoiceId)throws XbbException{
        return purchaseInvoiceHelp.getAddOrDeleteRelationship(newData, oldData, corpid, invoiceId);
    }

    /*private void checkRefNotPurchaseInvoiceAmount(JSONObject data,Double totalMoney,Integer isImport) throws XbbException{
        if(Objects.equals(totalMoney,BasicConstant.ZERO_DOUBLE)){
            if(Objects.equals(isImport,BasicConstant.ZERO)){
                if(Objects.nonNull(data)){
                    if(CollectionsUtil.isNotEmpty(data.getJSONArray(PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr()))){
                        JSONArray supplierArray = data.getJSONArray(PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr());
                        checkInvice
                    }
                }
            }
        }
    }*/

   /* private void checkPurchaseInvoice(JSONArray refArray, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException{
        String amountAttr = null;
        String purchaseInvoiceAmountAttr = null;
        if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.SUPPLIER)){

        }
    }*/


    private void formatPurchaseInvoiceLinkBusiness4Save(JSONObject data) throws XbbException{
        saasSaveHelp.formatLinkBusiness4SaveByArray(data,PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(),PurchaseInvoiceEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(),PurchaseInvoiceEnum.SUPPLIER_NAME.getFieldType());
        saasSaveHelp.formatLinkBusiness4SaveByArray(data,PurchaseInvoiceEnum.PURCHASE_ID.getAttr(), PurchaseInvoiceEnum.PURCHASE_ID_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.PURCHASE_ID.getFieldType());
        saasSaveHelp.formatLinkBusiness4SaveByArray(data,PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr(), PurchaseInvoiceEnum.PAY_PLAN_ID_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.PAY_PLAN_ID.getFieldType());
        saasSaveHelp.formatLinkBusiness4SaveByArray(data,PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr(),PurchaseInvoiceEnum.PAY_SHEET_ID_LINK_TEXT.getAttr(),PurchaseInvoiceEnum.PAY_SHEET_ID.getFieldType());
    }



    /**
     * 发票编辑的时候老发票如果被删除可以先进行累加在从发票金额上减去
     * @param corpid 公司编号
     * @param invoiceId 发票id
     * @param idList 关联id 集合
     * @param refTypeEnum 关联的枚举类型
     * @throws XbbException
     */
    private void invoiceEditAmountCompute(String corpid,Long invoiceId,List<Long> idList,RefTypeEnum refTypeEnum) throws XbbException{
        if(CollectionsUtil.isEmpty(idList)){
            return;
        }
        RefTypePojo refTypePojo = getRefType(refTypeEnum);
        PurchaseInvoiceEnum purchaseInvoiceEnum = refTypePojo.getPurchaseInvoiceEnum();
        Integer businessType = refTypePojo.getBusinessType();
        String attr = refTypePojo.getInvoiceAmountAttr();
        Map<Long, PaasFormDataEntityExt> purchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //除这次发票之外其它发票关联了这些关系的发票关系map
        Map<Long, List<PurchaseInvoiceRelationshipEntity>> oldInvoiceMap = getInvoiceMap(corpid, invoiceId, idList,purchaseInvoiceEnum);
        if(Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode())){
            List<PaasFormDataEntityExt> contractList = paasEsModel.getByIdList(idList, corpid, SaasMarkEnum.SAAS.getCode(), businessType, new ArrayList<>(), IndexTypeEnum.IDX_SAAS_PURCHASE);
            contractList.forEach(contract-> purchaseMap.put(contract.getId(), contract));
        }
        for (Long id : idList) {
            List<PurchaseInvoiceRelationshipEntity>  singleRelationInvoiceList = oldInvoiceMap.get(id);
            Double otherInvoiceSumAmount = 0D;
            if (CollectionsUtil.isNotEmpty(singleRelationInvoiceList)) {
                for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : singleRelationInvoiceList) {
                    otherInvoiceSumAmount = Arith.add(otherInvoiceSumAmount,purchaseInvoiceRelationshipEntity.getMoney());
                }
            }
            if(Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode())) {
                JSONObject jsonObject = new JSONObject();
                if (Objects.nonNull(purchaseMap.get(id))) {
                    jsonObject.put(PurchaseEnum.INVOICE_AMOUNT.getAttr(), otherInvoiceSumAmount);
                    Double amount = purchaseMap.get(id).getData().getDouble(ContractEnum.AMOUNT.getAttr());
                    jsonObject.put(PurchaseEnum.UN_INVOICE_AMOUNT.getAttr(), amount - otherInvoiceSumAmount);
                    proUpdateHelp.update(businessType, corpid, id, jsonObject);
                }
            }else {
                proUpdateHelp.update(businessType, corpid, id, attr, otherInvoiceSumAmount);
            }
        }
    }

    /**
     * 获取发票的关联类型pojo
     * @param refTypeEnum
     * @return
     * @throws XbbException
     */
    private RefTypePojo getRefType(RefTypeEnum refTypeEnum) throws XbbException{
        RefTypePojo refTypePojo = new RefTypePojo();
        switch (refTypeEnum){
            case PURCHASE:
                refTypePojo.setBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
                refTypePojo.setPurchaseInvoiceEnum(PurchaseInvoiceEnum.PURCHASE_ID);
                refTypePojo.setInvoiceAmountAttr(PurchaseEnum.INVOICE_AMOUNT.getAttr());
                refTypePojo.setAmountAttr(PurchaseEnum.TOTAL_MONEY.getAttr());
                break;
            case PAYPLAN:
                refTypePojo.setBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
                refTypePojo.setPurchaseInvoiceEnum(PurchaseInvoiceEnum.PAY_PLAN_ID);
                refTypePojo.setInvoiceAmountAttr(PayPlanEnum.INVOICE_AMOUNT.getAttr());
                refTypePojo.setAmountAttr(PayPlanEnum.AMOUNT.getAttr());
                break;
            case PAYSHEET:
                refTypePojo.setBusinessType(XbbRefTypeEnum.PAY_SHEET.getCode());
                refTypePojo.setPurchaseInvoiceEnum(PurchaseInvoiceEnum.PAY_SHEET_ID);
                refTypePojo.setInvoiceAmountAttr(PaySheetEnum.INVOICE_AMOUNT.getAttr());
                refTypePojo.setAmountAttr(PaySheetEnum.AMOUNT.getAttr());
                break;
            default:
                throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216021);
        }
        return refTypePojo;
    }



    /**
     * 获取红冲总金额
     *
     * @param originIdIn 原始id
     * @param corpid   公司id
     * @return double
     * @throws XbbException 异常
     */
    @Override
    public Map<Long, Double> getRedTotalMoneyByIdIn(List<Long> originIdIn,List<Long> negIdIn, String corpid) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT + PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), originIdIn));
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD , corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        if (CollectionsUtil.isNotEmpty(negIdIn)){
            boolQueryBuilder.filter(boolQuery().mustNot(termsQuery(FieldTypeEnum.DATAID.getAlias(), negIdIn)));
        }
        List<String> fieldList = new ArrayList<>();
        fieldList.add(PurchaseInvoiceEnum.getAttrConnectData(PurchaseInvoiceEnum.ORIGIN_ID));
        fieldList.add(PurchaseInvoiceEnum.getAttrConnectData(PurchaseInvoiceEnum.TOTAL_MONEY));
        List<PaasFormDataEntityExt> originInvoiceList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        Map<Long, Double> redMoneyMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Long originId;
        Double money;
        for (PaasFormDataEntityExt paasFormDataEntityExt : originInvoiceList) {
            originId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), 0L);
            money = getDoubleOrDefaultFromFormData(paasFormDataEntityExt.getData(), PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(), 0D);
            if (redMoneyMap.containsKey(originId)) {
                money = redMoneyMap.get(originId) + money;
            }
            redMoneyMap.put(originId, money);
        }
        return redMoneyMap;
    }
    /**
     * 根据采购合同id/付款计划id/付款单id 放入一个map 对应的值为开票的关联实体
     * @param corpid
     * @param invoiceId
     * @param oldRelationIdList
     * @param purchaseInvoiceEnum
     * @return
     * @throws XbbException
     */
    private Map<Long, List<PurchaseInvoiceRelationshipEntity>> getInvoiceMap(String corpid, Long invoiceId, List<Long> oldRelationIdList,PurchaseInvoiceEnum purchaseInvoiceEnum) throws XbbException {
        return purchaseInvoiceHelp.getInvoiceMap(corpid, invoiceId, oldRelationIdList, purchaseInvoiceEnum);
    }

    public List<PurchaseInvoiceRelationshipEntity> getRelationShipInvoice(Long purchaseInvoiceId, String corpid, List<Long> relationIdList,PurchaseInvoiceEnum purchaseInvoiceEnum) throws XbbException {
        return purchaseInvoiceHelp.getRelationShipInvoice(purchaseInvoiceId, corpid, relationIdList, purchaseInvoiceEnum);
    }



    @Override
    public PurchaseInvoiceAmountDetailVO getPurchaseInvoiceAmountDetail(PurchaseInvoiceAmountDetailGetDTO purchaseInvoiceAmountDetailGetDTO) throws XbbException {
        return purchaseInvoiceModel.getPurchaseInvoiceAmountDetail(purchaseInvoiceAmountDetailGetDTO);
    }

    @Override
    public InvoiceGetByPurchaseIdVO getByPurchase(InvoiceGetByPurchaseIdDTO invoiceGetByPurchaseIdDTO) throws XbbException {
        Long purchaseId = invoiceGetByPurchaseIdDTO.getPurchaseId();
        String corpid = invoiceGetByPurchaseIdDTO.getCorpid();
        List<Long> purchaseIds = new ArrayList<>();
        List<Long> invoiceIds = new ArrayList<>();
        purchaseIds.add(purchaseId);
        InvoiceGetByPurchaseIdVO invoiceGetByPurchaseIdVO = new InvoiceGetByPurchaseIdVO();
        UserVO userVo = invoiceGetByPurchaseIdDTO.getLoginUser();
        Set<String> permSet = userVo.getPermSet();
        int total = 0;
        List<PaasFormDataEntityExt> results = new ArrayList<>();
        if(permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_VIEW.getAlias())) {
            //根据合同ID获取正常发票列表
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = getNormalPurchaseInvoiceListByEs(corpid, purchaseIds, invoiceGetByPurchaseIdDTO);
            results = esEntities.getContent();
            results.forEach(e -> invoiceIds.add(e.getDataId()));
            //根据发票ID获取发票已红冲金额(负数)
            Map<Long, Double> redTotalMoneyByIdMap = getRedTotalMoneyByIdIn(invoiceIds, new ArrayList<>(), corpid);
            Iterator<PaasFormDataEntityExt> iterator = esEntities.getContent().iterator();
            while (iterator.hasNext()){
                PaasFormDataEntityExt paasFormDataEntityExt = iterator.next();
                Long dataId = paasFormDataEntityExt.getDataId();
                JSONObject data = paasFormDataEntityExt.getData();
                Double amount = getDoubleOrDefaultFromFormData(data, PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(), 0D);
                Double redAmount = redTotalMoneyByIdMap.get(dataId);
                if(redAmount != null && amount != null){
                    //判断该发票是否还允许红冲
                    double money = amount + redAmount;
                    if(money <= 0){
                        iterator.remove();
                    }
                }
            }
            total = (int)esEntities.getTotalElements();
        }
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Integer businessType = paasFormExplainEntity.getBusinessType();
        //fieldList处理
        List<String> fieldList = BusinessFieldEnum.getByBusinessType(businessType);
        fieldList = saasListHelp.dealFieldList(fieldList, businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), null);
        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
        paasFormEntityExt.setBusinessName(XbbRefTypeEnum.getByCode(businessType).getName());
        paasFormEntityExt.setMainAttr(ReturnedPurchaseEnum.SHEET_NO.getAttr());
        paasFormEntityExt.setMenuId(paasFormExplainEntity.getMenuId());
        paasFormEntityExt.setId(paasFormExplainEntity.getFormId());
        paasFormEntityExt.setAppId(paasFormExplainEntity.getAppId());
        paasFormEntityExt.setBusinessType(paasFormExplainEntity.getBusinessType());
        explainList = explainHelp.handleExplain(explainList, fieldList, paasFormEntityExt);
        invoiceGetByPurchaseIdVO.setHeadList(explainList);
        // 新建权限
        VerifyAddPermissionDTO verifyAddPermissionDTO = new VerifyAddPermissionDTO();
        // 这里只有赋值，没有copy
        verifyAddPermissionDTO.setSaasMark(paasFormExplainEntity.getSaasMark());
        verifyAddPermissionDTO.setBusinessType(businessType);
        verifyAddPermissionDTO.setMenuId(paasFormExplainEntity.getMenuId());
        verifyAddPermissionDTO.setLoginUser(userVo);
        verifyAddPermissionDTO.setSaasMark(paasFormExplainEntity.getSaasMark());
        verifyAddPermissionDTO.setCorpid(corpid);
        List<ButtonPojo> buttonList = paasFormHelp.getAddButton(verifyAddPermissionDTO, paasFormExplainEntity.getAppId(), paasFormExplainEntity.getFormId());
        invoiceGetByPurchaseIdVO.setTopPermissions(buttonList);

        invoiceGetByPurchaseIdVO.setPaasFormDataESList(results);
        invoiceGetByPurchaseIdVO.setForm(paasFormEntityExt);
        invoiceGetByPurchaseIdVO.setBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
        //分页信息
        PageHelper pageHelper = PageHelperUtil.initPageHelper(total, invoiceGetByPurchaseIdDTO.getPage(), invoiceGetByPurchaseIdDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE);
        invoiceGetByPurchaseIdVO.setPageHelper(pageHelper);
        //作废/红冲按钮权限信息
        JSONObject invoiceCancelRedPermission = new JSONObject();
        invoiceCancelRedPermission.put(ProPermissionAliasEnum.PURCHASE_INVOICE_CANCEL.getAlias(), permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_CANCEL.getAlias()));
        invoiceCancelRedPermission.put(ProPermissionAliasEnum.PURCHASE_INVOICE_RED.getAlias(), permSet.contains(ProPermissionAliasEnum.PURCHASE_INVOICE_RED.getAlias()));
        invoiceGetByPurchaseIdVO.setInvoiceCancelRedPermission(invoiceCancelRedPermission);
        return invoiceGetByPurchaseIdVO;
    }

/*    @Override
    public PurchaseInvoiceAmountDetailVO getPurchaseInvoiceAmountDetail(PurchaseInvoiceAmountDetailGetDTO purchaseInvoiceAmountDetailGetDTO) throws XbbException{
        //1确认是什么发票
        if(!Objects.equals(purchaseInvoiceAmountDetailGetDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
            throw new XbbException(ErrorCodeEnum.API_ERROR_361001);
        }
        List<PaasFormDataEntityExt> paasFormDataEntityExts = null;
        List<Object> relationshipList = null;
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<InvoiceAmountDetailDTO> amountDetail = new ArrayList<>();
        Map<Long,PaasFormDataEntityExt> purchaseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Double purchaseInvoiceAmount = 0D;
        Double purchaseSumMoney = 0D;
        List<JSONObject> userList = new ArrayList<>();
        if(CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList())
                && CollectionsUtil.isEmpty(purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList()) && CollectionsUtil.isEmpty(purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList())){
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            param.put("corpid",purchaseInvoiceAmountDetailGetDTO.getCorpid());
            param.put("del",DelEnum.NORMAL.getDel());
            List<PurchaseEntityExt> purchaseEntityExts = purchaseModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseEntityExts)) {
                for (PurchaseEntityExt purchaseEntityExt : purchaseEntityExts){
                    purchaseMap.put(purchaseEntityExt.getId(), purchaseEntityExt);
                    if (Objects.nonNull(purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr()))) {
                        purchaseSumMoney = Arith.add(purchaseSumMoney, purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr()));
                    }
                }
            }
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getSupplierIdList());
            List<SupplierEntityExt> supplierEntityExts = supplierModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(supplierEntityExts)) {
                for(SupplierEntityExt supplierEntityExt : supplierEntityExts) {
                    JSONObject data = supplierEntityExt.getData();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(BasicConstant.ID,supplierEntityExt.getId());
                    jsonObject.put(BasicConstant.NAME,FastJsonHelper.getStringOrDefaultFromFormData(data,SupplierEnum.SUPPLIER_NAME.getAttr(),""));
                    userList.add(jsonObject);
                }
            }
            param.put("purchaseIdIn",purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)) {
                param.put("purchaseInvoiceIdNot",purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
            }
            param.remove("idIn");
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)){
                for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities){
                    //saasSaveHelp.addMapNormal(purchaseInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseInvoiceRelationshipEntity.getMoney());
                    Arith.add(purchaseInvoiceAmount,purchaseInvoiceRelationshipEntity.getMoney());
                }
            }
            paasFormDataEntityExts = new ArrayList<>(purchaseEntityExts);
            relationshipList = new ArrayList<>(purchaseInvoiceRelationshipEntities);
            amountDetail = invoiceCommonHelper.commonPackageAmountDetail(paasFormDataEntityExts,relationshipList,null,purchaseSumMoney,purchaseInvoiceAmount,userList,XbbRefTypeEnum.PURCHASE.getCode(),purchaseInvoiceAmountDetailGetDTO.getIsRed(),purchaseInvoiceAmountDetailGetDTO.getIsEdit());
        }
        if(CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList())
                && CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList()) && CollectionsUtil.isEmpty(purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList())){
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList());
            param.put("corpid",purchaseInvoiceAmountDetailGetDTO.getCorpid());
            param.put("del",DelEnum.NORMAL.getDel());
            List<PayPlanEntityExt> payPlanEntityExts = payPlanModel.findEntitys(param);
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getSupplierIdList());
            List<SupplierEntityExt> supplierEntityExts = supplierModel.findEntitys(param);
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            List<PurchaseEntityExt> purchaseEntityExts = purchaseModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseEntityExts)) {
                for (PurchaseEntityExt purchaseEntityExt : purchaseEntityExts){
                    purchaseMap.put(purchaseEntityExt.getId(), purchaseEntityExt);
                    if (Objects.nonNull(purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr()))) {
                        purchaseSumMoney = Arith.add(purchaseSumMoney, purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr()));
                    }
                }
            }
            if(CollectionsUtil.isNotEmpty(supplierEntityExts)) {
                for(SupplierEntityExt supplierEntityExt : supplierEntityExts) {
                    JSONObject data = supplierEntityExt.getData();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(BasicConstant.ID,supplierEntityExt.getId());
                    jsonObject.put(BasicConstant.NAME,FastJsonHelper.getStringOrDefaultFromFormData(data,SupplierEnum.SUPPLIER_NAME.getAttr(),""));
                    userList.add(jsonObject);
                }
            }
            param.put("payPlanIdIn",purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList());
            if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)) {
                param.put("purchaseInvoiceIdNot",purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
            }
            param.remove("idIn");
            List<PurchaseInvoiceRelationshipEntity> refInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            param.put("purchaseIdIn",purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            param.remove("payPlanIdIn");
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)){
                for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities){
                    //saasSaveHelp.addMapNormal(purchaseInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseInvoiceRelationshipEntity.getMoney());
                    Arith.add(purchaseInvoiceAmount,purchaseInvoiceRelationshipEntity.getMoney());
                }
            }
            paasFormDataEntityExts = new ArrayList<>(payPlanEntityExts);
            relationshipList = new ArrayList<>(refInvoiceRelationshipEntities);
            amountDetail = invoiceCommonHelper.commonPackageAmountDetail(paasFormDataEntityExts,relationshipList,purchaseMap,purchaseSumMoney,purchaseInvoiceAmount,userList,XbbRefTypeEnum.PAY_PLAN.getCode(),purchaseInvoiceAmountDetailGetDTO.getIsRed(),purchaseInvoiceAmountDetailGetDTO.getIsEdit());
        }
        if(CollectionsUtil.isEmpty(purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList()) && CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList())){
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList());
            param.put("corpid",purchaseInvoiceAmountDetailGetDTO.getCorpid());
            param.put("del",DelEnum.NORMAL.getDel());
            List<PayPlanSheetEntityExt> payPlanSheetEntityExts = paySheetModel.findEntitys(param);
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getSupplierIdList());
            List<SupplierEntityExt> supplierEntityExts = supplierModel.findEntitys(param);
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            List<PurchaseEntityExt> purchaseEntityExts = purchaseModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseEntityExts)) {
                for (PurchaseEntityExt purchaseEntityExt : purchaseEntityExts){
                    purchaseMap.put(purchaseEntityExt.getId(), purchaseEntityExt);
                    if (Objects.nonNull(purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr()))) {
                        purchaseSumMoney = Arith.add(purchaseSumMoney, purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr()));
                    }
                }
            }
            if(CollectionsUtil.isNotEmpty(supplierEntityExts)) {
                for(SupplierEntityExt supplierEntityExt : supplierEntityExts) {
                    JSONObject data = supplierEntityExt.getData();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(BasicConstant.ID,supplierEntityExt.getId());
                    jsonObject.put(BasicConstant.NAME,FastJsonHelper.getStringOrDefaultFromFormData(data,SupplierEnum.SUPPLIER_NAME.getAttr(),""));
                    userList.add(jsonObject);
                }
            }
            param.put("paySheetIdIn", purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)) {
               param.put("purchaseInvoiceIdNot",purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
            }
            param.remove("idIn");
            List<PurchaseInvoiceRelationshipEntity> refInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList())) {
                param.put("purchaseIdIn", purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
                param.remove("paySheetIdIn");
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities){
                        Arith.add(purchaseInvoiceAmount,purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
            }else {
                if(CollectionsUtil.isNotEmpty(refInvoiceRelationshipEntities)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : refInvoiceRelationshipEntities){
                        Arith.add(purchaseInvoiceAmount,purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
            }
            paasFormDataEntityExts = new ArrayList<>(payPlanSheetEntityExts);
            relationshipList = new ArrayList<>(refInvoiceRelationshipEntities);
            amountDetail = invoiceCommonHelper.commonPackageAmountDetail(paasFormDataEntityExts,relationshipList,purchaseMap,purchaseSumMoney,purchaseInvoiceAmount,userList,XbbRefTypeEnum.PAY_SHEET.getCode(),purchaseInvoiceAmountDetailGetDTO.getIsRed(),purchaseInvoiceAmountDetailGetDTO.getIsEdit());
        }
        PurchaseInvoiceAmountDetailVO purchaseInvoiceAmountDetailVO = new PurchaseInvoiceAmountDetailVO();
        purchaseInvoiceAmountDetailVO.setAmountDetail(amountDetail);
        return purchaseInvoiceAmountDetailVO;
    }*/

    /**
     * 获取正常进项发票列表
     * @param corpid 公司ID
     * @param purchaseIds 采购合同ID数组
     * @param invoiceGetByPurchaseIdDTO 入参
     * @throws XbbException error
     * @return es查询结果
     */
    private XbbAggregatedPage<PaasFormDataEntityExt> getNormalPurchaseInvoiceListByEs(String corpid, List<Long> purchaseIds, InvoiceGetByPurchaseIdDTO invoiceGetByPurchaseIdDTO) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        BoolQueryBuilder teamQueryBuilder = boolQuery();
        teamQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        List<ConditionsEntityExt> conditions = new ArrayList<>();
        //数据权限判断
        TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), null, invoiceGetByPurchaseIdDTO.getDistributorMark());
        saasListDataPermissionHelp.listDataPermission(conditions, invoiceGetByPurchaseIdDTO.getLoginUser(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
        EsUtil.parseCondition(boolQueryBuilder, conditions, null, corpid, XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery("data." + PurchaseInvoiceEnum.PURCHASE_ID.getAttr() + ".keyword", purchaseIds));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery("data." + PurchaseInvoiceEnum.IS_CANCEL.getAttr(), 0));
        boolQueryBuilder.filter(termQuery("data." + PurchaseInvoiceEnum.IS_RED.getAttr(), 0));
        boolQueryBuilder.filter(termsQuery("flowStatus",Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        String serialNo = invoiceGetByPurchaseIdDTO.getSerialNo();
        if(serialNo != null && !Objects.equals(serialNo, "")){
            boolQueryBuilder.filter(matchPhraseQuery("serialNo", serialNo));
        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, invoiceGetByPurchaseIdDTO.getPage(), invoiceGetByPurchaseIdDTO.getPageSize());
        searchRequest.source(sourceBuilder);
        return xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
    }


    @Override
    public void dataConsistencyUpdatePurchase(String corpid, Long purchaseId, String serialNo) {
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery(PurchaseInvoiceEnum.getEsAttr4Keyword(PurchaseInvoiceEnum.PURCHASE_ID), purchaseId));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            List<PurchaseInvoiceEntityExt> purchaseInvoiceEntityExtList = purchaseInvoiceModel.findEntitys(param);
            if (Objects.nonNull(purchaseInvoiceEntityExtList) && !purchaseInvoiceEntityExtList.isEmpty()) {
                List<PurchaseInvoiceUpdateDTO> purchaseInvoiceUpdateDTOList = new ArrayList<>();
                for (PurchaseInvoiceEntityExt entityExt : purchaseInvoiceEntityExtList) {
                    JSONObject oldData = entityExt.getData();
                    if (oldData == null) {
                        continue;
                    }
                    List<Long> idList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, PurchaseInvoiceEnum.PURCHASE_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
                    List<String> noList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData,PurchaseInvoiceEnum.PURCHASE_ID_LINK_TEXT.getAttr(), new JSONArray()).toJavaList(String.class);
                    for (int i = 0; i < idList.size(); i++) {
                        Long cid = idList.get(i);
                        if (Objects.equals(cid, purchaseId)) {
                            noList.set(i, serialNo);
                        }
                    }

                    PurchaseInvoiceUpdateDTO purchaseInvoiceUpdateDTO = new PurchaseInvoiceUpdateDTO();
                    purchaseInvoiceUpdateDTO.setId(entityExt.getId());
                    JSONObject data = new JSONObject();
                    data.put(PurchaseInvoiceEnum.PURCHASE_ID_LINK_TEXT.getAttr(), noList);
                    purchaseInvoiceUpdateDTO.setData(data);
                    purchaseInvoiceUpdateDTOList.add(purchaseInvoiceUpdateDTO);
                }
                PurchaseInvoiceUpdateBatchDTO purchaseInvoiceUpdateBatchDTO = new PurchaseInvoiceUpdateBatchDTO();
                purchaseInvoiceUpdateBatchDTO.setCorpid(corpid);
                purchaseInvoiceUpdateBatchDTO.setInvoiceList(purchaseInvoiceUpdateDTOList);
                updateBatch(purchaseInvoiceUpdateBatchDTO);
            }
        } catch (Exception e) {
            LOG.error("PurchaseInvoiceServiceImpl.dataConsistencyUpdatePurchase fail， corpid=" + corpid + " purchaseId=" + purchaseId + "  purchaseNo=" + serialNo, e);
        }
    }

    @Override
    public void dataConsistencyUpdatePayPlan(String corpid, Long payPlanId, String serialNo) {
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery(PurchaseInvoiceEnum.getEsAttr4Keyword(PurchaseInvoiceEnum.PAY_PLAN_ID), payPlanId));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            List<PurchaseInvoiceEntityExt> purchaseInvoiceEntityExtList = purchaseInvoiceModel.findEntitys(param);
            if (Objects.nonNull(purchaseInvoiceEntityExtList) && !purchaseInvoiceEntityExtList.isEmpty()) {
                List<PurchaseInvoiceUpdateDTO> purchaseInvoiceUpdateDTOList = new ArrayList<>();
                for (PurchaseInvoiceEntityExt entityExt : purchaseInvoiceEntityExtList) {
                    JSONObject oldData = entityExt.getData();
                    if (oldData == null) {
                        continue;
                    }
                    List<Long> idList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
                    List<String> noList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData,PurchaseInvoiceEnum.PAY_PLAN_ID_LINK_TEXT.getAttr(), new JSONArray()).toJavaList(String.class);
                    for (int i = 0; i < idList.size(); i++) {
                        Long cid = idList.get(i);
                        if (Objects.equals(cid, payPlanId)) {
                            noList.set(i, serialNo);
                        }
                    }

                    PurchaseInvoiceUpdateDTO purchaseInvoiceUpdateDTO = new PurchaseInvoiceUpdateDTO();
                    purchaseInvoiceUpdateDTO.setId(entityExt.getId());
                    JSONObject data = new JSONObject();
                    data.put(PurchaseInvoiceEnum.PAY_PLAN_ID_LINK_TEXT.getAttr(), noList);
                    purchaseInvoiceUpdateDTO.setData(data);
                    purchaseInvoiceUpdateDTOList.add(purchaseInvoiceUpdateDTO);
                }
                PurchaseInvoiceUpdateBatchDTO purchaseInvoiceUpdateBatchDTO = new PurchaseInvoiceUpdateBatchDTO();
                purchaseInvoiceUpdateBatchDTO.setCorpid(corpid);
                purchaseInvoiceUpdateBatchDTO.setInvoiceList(purchaseInvoiceUpdateDTOList);
                updateBatch(purchaseInvoiceUpdateBatchDTO);
            }
        } catch (Exception e) {
            LOG.error("PurchaseInvoiceServiceImpl.dataConsistencyUpdatePayPlan fail， corpid=" + corpid + " payPlanId=" + payPlanId + "  payPlanNo=" + serialNo, e);
        }
    }
    @Override
    public void updateBatchLabelAttr(AddLabelDTO addLabelDTO, List<PaasFormDataEntityExt> addBatchList, Boolean addOrDelete) throws XbbException {
        PurchaseInvoiceUpdateBatchDTO purchaseInvoiceUpdateBatchDTO = new PurchaseInvoiceUpdateBatchDTO();
        BeanUtil.copyProperties(addLabelDTO, purchaseInvoiceUpdateBatchDTO);
        List<PurchaseInvoiceUpdateDTO> purchaseInvoiceList = new ArrayList<>();
        addBatchList.forEach(item ->{
            PurchaseInvoiceUpdateDTO purchaseInvoiceUpdateDTO = new PurchaseInvoiceUpdateDTO();
            purchaseInvoiceUpdateDTO.setData(item.getData());
            purchaseInvoiceUpdateDTO.setId(item.getId());
            purchaseInvoiceList.add(purchaseInvoiceUpdateDTO);
        });
        purchaseInvoiceUpdateBatchDTO.setInvoiceList(purchaseInvoiceList);
        updateBatch(purchaseInvoiceUpdateBatchDTO);

    }

    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        String corpid = saasFormSaveDTO.getCorpid();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long purchaseInvoiceId = newPaasFormDataEntity.getId();

        InvoiceRelationshipEditPojo invoiceRelationshipEditPojo = getAddOrDeleteRelationship(newData,oldData,corpid,purchaseInvoiceId);

        try {
//            Long originId = FastJsonHelper.getLongOrDefaultFromFormData(newData,PurchaseInvoiceEnum.ORIGIN_ID.getAttr(),0L);
//            if (originId > BasicConstant.ZERO) {
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(PurchaseInvoiceEnum.HAS_RED.getAttr(), BasicConstant.ONE);
//                UpdateDataEntity updateData = ExplainUtil.getUpdateData(originId, jsonObject, corpid);
//                purchaseInvoiceModel.updateBatch(Collections.singletonList(updateData), corpid);
//                jsonObject = new JSONObject();
//                jsonObject.put(PurchaseInvoiceEnum.IS_RED.getAttr(), BasicConstant.ONE);
//                UpdateDataEntity updateData1 = ExplainUtil.getUpdateData(purchaseInvoiceId, jsonObject, corpid);
//                purchaseInvoiceModel.updateBatch(Collections.singletonList(updateData1), corpid);
//            }
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo();
            //审批的时候只能从 saasNeedPojo 拿
            if(CollectionsUtil.isNotEmpty(saasNeedRedundantAttrPojo.getAmountDetail())){
                saasFormSaveDTO.setAmountDetail(saasNeedRedundantAttrPojo.getAmountDetail());
            }

        } catch (Exception e){
            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
            LOG.error("PurchaseInvoiceServiceImpl.afterSave 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {

    }
}
